babylon.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var r = start.r + ((end.r - start.r) * amount);
  1781. var g = start.g + ((end.g - start.g) * amount);
  1782. var b = start.b + ((end.b - start.b) * amount);
  1783. return new Color3(r, g, b);
  1784. };
  1785. /**
  1786. * Returns a Color3 value containing a red color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Red = function () { return new Color3(1, 0, 0); };
  1790. /**
  1791. * Returns a Color3 value containing a green color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Green = function () { return new Color3(0, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a blue color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a black color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Black = function () { return new Color3(0, 0, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a white color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.White = function () { return new Color3(1, 1, 1); };
  1810. /**
  1811. * Returns a Color3 value containing a purple color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1815. /**
  1816. * Returns a Color3 value containing a magenta color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1820. /**
  1821. * Returns a Color3 value containing a yellow color
  1822. * @returns a new Color3 object
  1823. */
  1824. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1825. /**
  1826. * Returns a Color3 value containing a gray color
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1830. /**
  1831. * Returns a Color3 value containing a teal color
  1832. * @returns a new Color3 object
  1833. */
  1834. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1835. /**
  1836. * Returns a Color3 value containing a random color
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1840. return Color3;
  1841. }());
  1842. BABYLON.Color3 = Color3;
  1843. /**
  1844. * Class used to hold a RBGA color
  1845. */
  1846. var Color4 = /** @class */ (function () {
  1847. /**
  1848. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1849. * @param r defines the red component (between 0 and 1, default is 0)
  1850. * @param g defines the green component (between 0 and 1, default is 0)
  1851. * @param b defines the blue component (between 0 and 1, default is 0)
  1852. * @param a defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. function Color4(
  1855. /**
  1856. * Defines the red component (between 0 and 1, default is 0)
  1857. */
  1858. r,
  1859. /**
  1860. * Defines the green component (between 0 and 1, default is 0)
  1861. */
  1862. g,
  1863. /**
  1864. * Defines the blue component (between 0 and 1, default is 0)
  1865. */
  1866. b,
  1867. /**
  1868. * Defines the alpha component (between 0 and 1, default is 1)
  1869. */
  1870. a) {
  1871. if (r === void 0) { r = 0; }
  1872. if (g === void 0) { g = 0; }
  1873. if (b === void 0) { b = 0; }
  1874. if (a === void 0) { a = 1; }
  1875. this.r = r;
  1876. this.g = g;
  1877. this.b = b;
  1878. this.a = a;
  1879. }
  1880. // Operators
  1881. /**
  1882. * Adds in place the given Color4 values to the current Color4 object
  1883. * @param right defines the second operand
  1884. * @returns the current updated Color4 object
  1885. */
  1886. Color4.prototype.addInPlace = function (right) {
  1887. this.r += right.r;
  1888. this.g += right.g;
  1889. this.b += right.b;
  1890. this.a += right.a;
  1891. return this;
  1892. };
  1893. /**
  1894. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1895. * @returns the new array
  1896. */
  1897. Color4.prototype.asArray = function () {
  1898. var result = new Array();
  1899. this.toArray(result, 0);
  1900. return result;
  1901. };
  1902. /**
  1903. * Stores from the starting index in the given array the Color4 successive values
  1904. * @param array defines the array where to store the r,g,b components
  1905. * @param index defines an optional index in the target array to define where to start storing values
  1906. * @returns the current Color4 object
  1907. */
  1908. Color4.prototype.toArray = function (array, index) {
  1909. if (index === undefined) {
  1910. index = 0;
  1911. }
  1912. array[index] = this.r;
  1913. array[index + 1] = this.g;
  1914. array[index + 2] = this.b;
  1915. array[index + 3] = this.a;
  1916. return this;
  1917. };
  1918. /**
  1919. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1920. * @param right defines the second operand
  1921. * @returns a new Color4 object
  1922. */
  1923. Color4.prototype.add = function (right) {
  1924. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1925. };
  1926. /**
  1927. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1928. * @param right defines the second operand
  1929. * @returns a new Color4 object
  1930. */
  1931. Color4.prototype.subtract = function (right) {
  1932. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1933. };
  1934. /**
  1935. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1936. * @param right defines the second operand
  1937. * @param result defines the Color4 object where to store the result
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.subtractToRef = function (right, result) {
  1941. result.r = this.r - right.r;
  1942. result.g = this.g - right.g;
  1943. result.b = this.b - right.b;
  1944. result.a = this.a - right.a;
  1945. return this;
  1946. };
  1947. /**
  1948. * Creates a new Color4 with the current Color4 values multiplied by scale
  1949. * @param scale defines the scaling factor to apply
  1950. * @returns a new Color4 object
  1951. */
  1952. Color4.prototype.scale = function (scale) {
  1953. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1954. };
  1955. /**
  1956. * Multiplies the current Color4 values by scale and stores the result in "result"
  1957. * @param scale defines the scaling factor to apply
  1958. * @param result defines the Color4 object where to store the result
  1959. * @returns the current unmodified Color4
  1960. */
  1961. Color4.prototype.scaleToRef = function (scale, result) {
  1962. result.r = this.r * scale;
  1963. result.g = this.g * scale;
  1964. result.b = this.b * scale;
  1965. result.a = this.a * scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Scale the current Color4 values by a factor and add the result to a given Color4
  1970. * @param scale defines the scale factor
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the unmodified current Color4
  1973. */
  1974. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1975. result.r += this.r * scale;
  1976. result.g += this.g * scale;
  1977. result.b += this.b * scale;
  1978. result.a += this.a * scale;
  1979. return this;
  1980. };
  1981. /**
  1982. * Clamps the rgb values by the min and max values and stores the result into "result"
  1983. * @param min defines minimum clamping value (default is 0)
  1984. * @param max defines maximum clamping value (default is 1)
  1985. * @param result defines color to store the result into.
  1986. * @returns the cuurent Color4
  1987. */
  1988. Color4.prototype.clampToRef = function (min, max, result) {
  1989. if (min === void 0) { min = 0; }
  1990. if (max === void 0) { max = 1; }
  1991. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1992. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1993. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1994. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1995. return this;
  1996. };
  1997. /**
  1998. * Multipy an Color4 value by another and return a new Color4 object
  1999. * @param color defines the Color4 value to multiply by
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.multiply = function (color) {
  2003. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2004. };
  2005. /**
  2006. * Multipy a Color4 value by another and push the result in a reference value
  2007. * @param color defines the Color4 value to multiply by
  2008. * @param result defines the Color4 to fill the result in
  2009. * @returns the result Color4
  2010. */
  2011. Color4.prototype.multiplyToRef = function (color, result) {
  2012. result.r = this.r * color.r;
  2013. result.g = this.g * color.g;
  2014. result.b = this.b * color.b;
  2015. result.a = this.a * color.a;
  2016. return result;
  2017. };
  2018. /**
  2019. * Creates a string with the Color4 current values
  2020. * @returns the string representation of the Color4 object
  2021. */
  2022. Color4.prototype.toString = function () {
  2023. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2024. };
  2025. /**
  2026. * Returns the string "Color4"
  2027. * @returns "Color4"
  2028. */
  2029. Color4.prototype.getClassName = function () {
  2030. return "Color4";
  2031. };
  2032. /**
  2033. * Compute the Color4 hash code
  2034. * @returns an unique number that can be used to hash Color4 objects
  2035. */
  2036. Color4.prototype.getHashCode = function () {
  2037. var hash = this.r || 0;
  2038. hash = (hash * 397) ^ (this.g || 0);
  2039. hash = (hash * 397) ^ (this.b || 0);
  2040. hash = (hash * 397) ^ (this.a || 0);
  2041. return hash;
  2042. };
  2043. /**
  2044. * Creates a new Color4 copied from the current one
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.prototype.clone = function () {
  2048. return new Color4(this.r, this.g, this.b, this.a);
  2049. };
  2050. /**
  2051. * Copies the given Color4 values into the current one
  2052. * @param source defines the source Color4 object
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.copyFrom = function (source) {
  2056. this.r = source.r;
  2057. this.g = source.g;
  2058. this.b = source.b;
  2059. this.a = source.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Copies the given float values into the current one
  2064. * @param r defines the red component to read from
  2065. * @param g defines the green component to read from
  2066. * @param b defines the blue component to read from
  2067. * @param a defines the alpha component to read from
  2068. * @returns the current updated Color4 object
  2069. */
  2070. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2071. this.r = r;
  2072. this.g = g;
  2073. this.b = b;
  2074. this.a = a;
  2075. return this;
  2076. };
  2077. /**
  2078. * Copies the given float values into the current one
  2079. * @param r defines the red component to read from
  2080. * @param g defines the green component to read from
  2081. * @param b defines the blue component to read from
  2082. * @param a defines the alpha component to read from
  2083. * @returns the current updated Color4 object
  2084. */
  2085. Color4.prototype.set = function (r, g, b, a) {
  2086. return this.copyFromFloats(r, g, b, a);
  2087. };
  2088. /**
  2089. * Compute the Color4 hexadecimal code as a string
  2090. * @returns a string containing the hexadecimal representation of the Color4 object
  2091. */
  2092. Color4.prototype.toHexString = function () {
  2093. var intR = (this.r * 255) | 0;
  2094. var intG = (this.g * 255) | 0;
  2095. var intB = (this.b * 255) | 0;
  2096. var intA = (this.a * 255) | 0;
  2097. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2098. };
  2099. /**
  2100. * Computes a new Color4 converted from the current one to linear space
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.toLinearSpace = function () {
  2104. var convertedColor = new Color4();
  2105. this.toLinearSpaceToRef(convertedColor);
  2106. return convertedColor;
  2107. };
  2108. /**
  2109. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2110. * @param convertedColor defines the Color4 object where to store the linear space version
  2111. * @returns the unmodified Color4
  2112. */
  2113. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2117. convertedColor.a = this.a;
  2118. return this;
  2119. };
  2120. /**
  2121. * Computes a new Color4 converted from the current one to gamma space
  2122. * @returns a new Color4 object
  2123. */
  2124. Color4.prototype.toGammaSpace = function () {
  2125. var convertedColor = new Color4();
  2126. this.toGammaSpaceToRef(convertedColor);
  2127. return convertedColor;
  2128. };
  2129. /**
  2130. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2131. * @param convertedColor defines the Color4 object where to store the gamma space version
  2132. * @returns the unmodified Color4
  2133. */
  2134. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2135. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2136. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2137. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2138. convertedColor.a = this.a;
  2139. return this;
  2140. };
  2141. // Statics
  2142. /**
  2143. * Creates a new Color4 from the string containing valid hexadecimal values
  2144. * @param hex defines a string containing valid hexadecimal values
  2145. * @returns a new Color4 object
  2146. */
  2147. Color4.FromHexString = function (hex) {
  2148. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2149. return new Color4(0.0, 0.0, 0.0, 0.0);
  2150. }
  2151. var r = parseInt(hex.substring(1, 3), 16);
  2152. var g = parseInt(hex.substring(3, 5), 16);
  2153. var b = parseInt(hex.substring(5, 7), 16);
  2154. var a = parseInt(hex.substring(7, 9), 16);
  2155. return Color4.FromInts(r, g, b, a);
  2156. };
  2157. /**
  2158. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2159. * @param left defines the start value
  2160. * @param right defines the end value
  2161. * @param amount defines the gradient factor
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.Lerp = function (left, right, amount) {
  2165. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2166. Color4.LerpToRef(left, right, amount, result);
  2167. return result;
  2168. };
  2169. /**
  2170. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2171. * @param left defines the start value
  2172. * @param right defines the end value
  2173. * @param amount defines the gradient factor
  2174. * @param result defines the Color4 object where to store data
  2175. */
  2176. Color4.LerpToRef = function (left, right, amount, result) {
  2177. result.r = left.r + (right.r - left.r) * amount;
  2178. result.g = left.g + (right.g - left.g) * amount;
  2179. result.b = left.b + (right.b - left.b) * amount;
  2180. result.a = left.a + (right.a - left.a) * amount;
  2181. };
  2182. /**
  2183. * Creates a new Color4 from the starting index element of the given array
  2184. * @param array defines the source array to read from
  2185. * @param offset defines the offset in the source array
  2186. * @returns a new Color4 object
  2187. */
  2188. Color4.FromArray = function (array, offset) {
  2189. if (offset === void 0) { offset = 0; }
  2190. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2191. };
  2192. /**
  2193. * Creates a new Color3 from integer values (< 256)
  2194. * @param r defines the red component to read from (value between 0 and 255)
  2195. * @param g defines the green component to read from (value between 0 and 255)
  2196. * @param b defines the blue component to read from (value between 0 and 255)
  2197. * @param a defines the alpha component to read from (value between 0 and 255)
  2198. * @returns a new Color3 object
  2199. */
  2200. Color4.FromInts = function (r, g, b, a) {
  2201. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2202. };
  2203. /**
  2204. * Check the content of a given array and convert it to an array containing RGBA data
  2205. * If the original array was already containing count * 4 values then it is returned directly
  2206. * @param colors defines the array to check
  2207. * @param count defines the number of RGBA data to expect
  2208. * @returns an array containing count * 4 values (RGBA)
  2209. */
  2210. Color4.CheckColors4 = function (colors, count) {
  2211. // Check if color3 was used
  2212. if (colors.length === count * 3) {
  2213. var colors4 = [];
  2214. for (var index = 0; index < colors.length; index += 3) {
  2215. var newIndex = (index / 3) * 4;
  2216. colors4[newIndex] = colors[index];
  2217. colors4[newIndex + 1] = colors[index + 1];
  2218. colors4[newIndex + 2] = colors[index + 2];
  2219. colors4[newIndex + 3] = 1.0;
  2220. }
  2221. return colors4;
  2222. }
  2223. return colors;
  2224. };
  2225. return Color4;
  2226. }());
  2227. BABYLON.Color4 = Color4;
  2228. /**
  2229. * Class representing a vector containing 2 coordinates
  2230. */
  2231. var Vector2 = /** @class */ (function () {
  2232. /**
  2233. * Creates a new Vector2 from the given x and y coordinates
  2234. * @param x defines the first coordinate
  2235. * @param y defines the second coordinate
  2236. */
  2237. function Vector2(
  2238. /** defines the first coordinate */
  2239. x,
  2240. /** defines the second coordinate */
  2241. y) {
  2242. if (x === void 0) { x = 0; }
  2243. if (y === void 0) { y = 0; }
  2244. this.x = x;
  2245. this.y = y;
  2246. }
  2247. /**
  2248. * Gets a string with the Vector2 coordinates
  2249. * @returns a string with the Vector2 coordinates
  2250. */
  2251. Vector2.prototype.toString = function () {
  2252. return "{X: " + this.x + " Y:" + this.y + "}";
  2253. };
  2254. /**
  2255. * Gets class name
  2256. * @returns the string "Vector2"
  2257. */
  2258. Vector2.prototype.getClassName = function () {
  2259. return "Vector2";
  2260. };
  2261. /**
  2262. * Gets current vector hash code
  2263. * @returns the Vector2 hash code as a number
  2264. */
  2265. Vector2.prototype.getHashCode = function () {
  2266. var hash = this.x || 0;
  2267. hash = (hash * 397) ^ (this.y || 0);
  2268. return hash;
  2269. };
  2270. // Operators
  2271. /**
  2272. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2273. * @param array defines the source array
  2274. * @param index defines the offset in source array
  2275. * @returns the current Vector2
  2276. */
  2277. Vector2.prototype.toArray = function (array, index) {
  2278. if (index === void 0) { index = 0; }
  2279. array[index] = this.x;
  2280. array[index + 1] = this.y;
  2281. return this;
  2282. };
  2283. /**
  2284. * Copy the current vector to an array
  2285. * @returns a new array with 2 elements: the Vector2 coordinates.
  2286. */
  2287. Vector2.prototype.asArray = function () {
  2288. var result = new Array();
  2289. this.toArray(result, 0);
  2290. return result;
  2291. };
  2292. /**
  2293. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2294. * @param source defines the source Vector2
  2295. * @returns the current updated Vector2
  2296. */
  2297. Vector2.prototype.copyFrom = function (source) {
  2298. this.x = source.x;
  2299. this.y = source.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Sets the Vector2 coordinates with the given floats
  2304. * @param x defines the first coordinate
  2305. * @param y defines the second coordinate
  2306. * @returns the current updated Vector2
  2307. */
  2308. Vector2.prototype.copyFromFloats = function (x, y) {
  2309. this.x = x;
  2310. this.y = y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given floats
  2315. * @param x defines the first coordinate
  2316. * @param y defines the second coordinate
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.set = function (x, y) {
  2320. return this.copyFromFloats(x, y);
  2321. };
  2322. /**
  2323. * Add another vector with the current one
  2324. * @param otherVector defines the other vector
  2325. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2326. */
  2327. Vector2.prototype.add = function (otherVector) {
  2328. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2332. * @param otherVector defines the other vector
  2333. * @param result defines the target vector
  2334. * @returns the unmodified current Vector2
  2335. */
  2336. Vector2.prototype.addToRef = function (otherVector, result) {
  2337. result.x = this.x + otherVector.x;
  2338. result.y = this.y + otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2343. * @param otherVector defines the other vector
  2344. * @returns the current updated Vector2
  2345. */
  2346. Vector2.prototype.addInPlace = function (otherVector) {
  2347. this.x += otherVector.x;
  2348. this.y += otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns a new Vector2
  2355. */
  2356. Vector2.prototype.addVector3 = function (otherVector) {
  2357. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2358. };
  2359. /**
  2360. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2361. * @param otherVector defines the other vector
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.subtract = function (otherVector) {
  2365. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2366. };
  2367. /**
  2368. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2369. * @param otherVector defines the other vector
  2370. * @param result defines the target vector
  2371. * @returns the unmodified current Vector2
  2372. */
  2373. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2374. result.x = this.x - otherVector.x;
  2375. result.y = this.y - otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @returns the current updated Vector2
  2382. */
  2383. Vector2.prototype.subtractInPlace = function (otherVector) {
  2384. this.x -= otherVector.x;
  2385. this.y -= otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Multiplies in place the current Vector2 coordinates by the given ones
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2394. this.x *= otherVector.x;
  2395. this.y *= otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.multiply = function (otherVector) {
  2404. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2405. };
  2406. /**
  2407. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2413. result.x = this.x * otherVector.x;
  2414. result.y = this.y * otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2419. * @param x defines the first coordinate
  2420. * @param y defines the second coordinate
  2421. * @returns a new Vector2
  2422. */
  2423. Vector2.prototype.multiplyByFloats = function (x, y) {
  2424. return new Vector2(this.x * x, this.y * y);
  2425. };
  2426. /**
  2427. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2428. * @param otherVector defines the other vector
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.divide = function (otherVector) {
  2432. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2433. };
  2434. /**
  2435. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @param result defines the target vector
  2438. * @returns the unmodified current Vector2
  2439. */
  2440. Vector2.prototype.divideToRef = function (otherVector, result) {
  2441. result.x = this.x / otherVector.x;
  2442. result.y = this.y / otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Divides the current Vector2 coordinates by the given ones
  2447. * @param otherVector defines the other vector
  2448. * @returns the current updated Vector2
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Gets a new Vector2 with current Vector2 negated coordinates
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.negate = function () {
  2458. return new Vector2(-this.x, -this.y);
  2459. };
  2460. /**
  2461. * Multiply the Vector2 coordinates by scale
  2462. * @param scale defines the scaling factor
  2463. * @returns the current updated Vector2
  2464. */
  2465. Vector2.prototype.scaleInPlace = function (scale) {
  2466. this.x *= scale;
  2467. this.y *= scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2472. * @param scale defines the scaling factor
  2473. * @returns a new Vector2
  2474. */
  2475. Vector2.prototype.scale = function (scale) {
  2476. var result = new Vector2(0, 0);
  2477. this.scaleToRef(scale, result);
  2478. return result;
  2479. };
  2480. /**
  2481. * Scale the current Vector2 values by a factor to a given Vector2
  2482. * @param scale defines the scale factor
  2483. * @param result defines the Vector2 object where to store the result
  2484. * @returns the unmodified current Vector2
  2485. */
  2486. Vector2.prototype.scaleToRef = function (scale, result) {
  2487. result.x = this.x * scale;
  2488. result.y = this.y * scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2493. * @param scale defines the scale factor
  2494. * @param result defines the Vector2 object where to store the result
  2495. * @returns the unmodified current Vector2
  2496. */
  2497. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2498. result.x += this.x * scale;
  2499. result.y += this.y * scale;
  2500. return this;
  2501. };
  2502. /**
  2503. * Gets a boolean if two vectors are equals
  2504. * @param otherVector defines the other vector
  2505. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2506. */
  2507. Vector2.prototype.equals = function (otherVector) {
  2508. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2509. };
  2510. /**
  2511. * Gets a boolean if two vectors are equals (using an epsilon value)
  2512. * @param otherVector defines the other vector
  2513. * @param epsilon defines the minimal distance to consider equality
  2514. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2515. */
  2516. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2517. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2518. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2519. };
  2520. /**
  2521. * Gets a new Vector2 from current Vector2 floored values
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.prototype.floor = function () {
  2525. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2526. };
  2527. /**
  2528. * Gets a new Vector2 from current Vector2 floored values
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.fract = function () {
  2532. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2533. };
  2534. // Properties
  2535. /**
  2536. * Gets the length of the vector
  2537. * @returns the vector length (float)
  2538. */
  2539. Vector2.prototype.length = function () {
  2540. return Math.sqrt(this.x * this.x + this.y * this.y);
  2541. };
  2542. /**
  2543. * Gets the vector squared length
  2544. * @returns the vector squared length (float)
  2545. */
  2546. Vector2.prototype.lengthSquared = function () {
  2547. return (this.x * this.x + this.y * this.y);
  2548. };
  2549. // Methods
  2550. /**
  2551. * Normalize the vector
  2552. * @returns the current updated Vector2
  2553. */
  2554. Vector2.prototype.normalize = function () {
  2555. var len = this.length();
  2556. if (len === 0)
  2557. return this;
  2558. var num = 1.0 / len;
  2559. this.x *= num;
  2560. this.y *= num;
  2561. return this;
  2562. };
  2563. /**
  2564. * Gets a new Vector2 copied from the Vector2
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.prototype.clone = function () {
  2568. return new Vector2(this.x, this.y);
  2569. };
  2570. // Statics
  2571. /**
  2572. * Gets a new Vector2(0, 0)
  2573. * @returns a new Vector2
  2574. */
  2575. Vector2.Zero = function () {
  2576. return new Vector2(0, 0);
  2577. };
  2578. /**
  2579. * Gets a new Vector2(1, 1)
  2580. * @returns a new Vector2
  2581. */
  2582. Vector2.One = function () {
  2583. return new Vector2(1, 1);
  2584. };
  2585. /**
  2586. * Gets a new Vector2 set from the given index element of the given array
  2587. * @param array defines the data source
  2588. * @param offset defines the offset in the data source
  2589. * @returns a new Vector2
  2590. */
  2591. Vector2.FromArray = function (array, offset) {
  2592. if (offset === void 0) { offset = 0; }
  2593. return new Vector2(array[offset], array[offset + 1]);
  2594. };
  2595. /**
  2596. * Sets "result" from the given index element of the given array
  2597. * @param array defines the data source
  2598. * @param offset defines the offset in the data source
  2599. * @param result defines the target vector
  2600. */
  2601. Vector2.FromArrayToRef = function (array, offset, result) {
  2602. result.x = array[offset];
  2603. result.y = array[offset + 1];
  2604. };
  2605. /**
  2606. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2607. * @param value1 defines 1st point of control
  2608. * @param value2 defines 2nd point of control
  2609. * @param value3 defines 3rd point of control
  2610. * @param value4 defines 4th point of control
  2611. * @param amount defines the interpolation factor
  2612. * @returns a new Vector2
  2613. */
  2614. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2615. var squared = amount * amount;
  2616. var cubed = amount * squared;
  2617. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2618. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2619. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2620. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2621. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2622. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2623. return new Vector2(x, y);
  2624. };
  2625. /**
  2626. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2627. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2628. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2629. * @param value defines the value to clamp
  2630. * @param min defines the lower limit
  2631. * @param max defines the upper limit
  2632. * @returns a new Vector2
  2633. */
  2634. Vector2.Clamp = function (value, min, max) {
  2635. var x = value.x;
  2636. x = (x > max.x) ? max.x : x;
  2637. x = (x < min.x) ? min.x : x;
  2638. var y = value.y;
  2639. y = (y > max.y) ? max.y : y;
  2640. y = (y < min.y) ? min.y : y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2645. * @param value1 defines the 1st control point
  2646. * @param tangent1 defines the outgoing tangent
  2647. * @param value2 defines the 2nd control point
  2648. * @param tangent2 defines the incoming tangent
  2649. * @param amount defines the interpolation factor
  2650. * @returns a new Vector2
  2651. */
  2652. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2653. var squared = amount * amount;
  2654. var cubed = amount * squared;
  2655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2657. var part3 = (cubed - (2.0 * squared)) + amount;
  2658. var part4 = cubed - squared;
  2659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2665. * @param start defines the start vector
  2666. * @param end defines the end vector
  2667. * @param amount defines the interpolation factor
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Lerp = function (start, end, amount) {
  2671. var x = start.x + ((end.x - start.x) * amount);
  2672. var y = start.y + ((end.y - start.y) * amount);
  2673. return new Vector2(x, y);
  2674. };
  2675. /**
  2676. * Gets the dot product of the vector "left" and the vector "right"
  2677. * @param left defines first vector
  2678. * @param right defines second vector
  2679. * @returns the dot product (float)
  2680. */
  2681. Vector2.Dot = function (left, right) {
  2682. return left.x * right.x + left.y * right.y;
  2683. };
  2684. /**
  2685. * Returns a new Vector2 equal to the normalized given vector
  2686. * @param vector defines the vector to normalize
  2687. * @returns a new Vector2
  2688. */
  2689. Vector2.Normalize = function (vector) {
  2690. var newVector = vector.clone();
  2691. newVector.normalize();
  2692. return newVector;
  2693. };
  2694. /**
  2695. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2696. * @param left defines 1st vector
  2697. * @param right defines 2nd vector
  2698. * @returns a new Vector2
  2699. */
  2700. Vector2.Minimize = function (left, right) {
  2701. var x = (left.x < right.x) ? left.x : right.x;
  2702. var y = (left.y < right.y) ? left.y : right.y;
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2707. * @param left defines 1st vector
  2708. * @param right defines 2nd vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Maximize = function (left, right) {
  2712. var x = (left.x > right.x) ? left.x : right.x;
  2713. var y = (left.y > right.y) ? left.y : right.y;
  2714. return new Vector2(x, y);
  2715. };
  2716. /**
  2717. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2718. * @param vector defines the vector to transform
  2719. * @param transformation defines the matrix to apply
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Transform = function (vector, transformation) {
  2723. var r = Vector2.Zero();
  2724. Vector2.TransformToRef(vector, transformation, r);
  2725. return r;
  2726. };
  2727. /**
  2728. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2729. * @param vector defines the vector to transform
  2730. * @param transformation defines the matrix to apply
  2731. * @param result defines the target vector
  2732. */
  2733. Vector2.TransformToRef = function (vector, transformation, result) {
  2734. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2735. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2736. result.x = x;
  2737. result.y = y;
  2738. };
  2739. /**
  2740. * Determines if a given vector is included in a triangle
  2741. * @param p defines the vector to test
  2742. * @param p0 defines 1st triangle point
  2743. * @param p1 defines 2nd triangle point
  2744. * @param p2 defines 3rd triangle point
  2745. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2746. */
  2747. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2748. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2749. var sign = a < 0 ? -1 : 1;
  2750. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2751. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2752. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2753. };
  2754. /**
  2755. * Gets the distance between the vectors "value1" and "value2"
  2756. * @param value1 defines first vector
  2757. * @param value2 defines second vector
  2758. * @returns the distance between vectors
  2759. */
  2760. Vector2.Distance = function (value1, value2) {
  2761. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2762. };
  2763. /**
  2764. * Returns the squared distance between the vectors "value1" and "value2"
  2765. * @param value1 defines first vector
  2766. * @param value2 defines second vector
  2767. * @returns the squared distance between vectors
  2768. */
  2769. Vector2.DistanceSquared = function (value1, value2) {
  2770. var x = value1.x - value2.x;
  2771. var y = value1.y - value2.y;
  2772. return (x * x) + (y * y);
  2773. };
  2774. /**
  2775. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2776. * @param value1 defines first vector
  2777. * @param value2 defines second vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Center = function (value1, value2) {
  2781. var center = value1.add(value2);
  2782. center.scaleInPlace(0.5);
  2783. return center;
  2784. };
  2785. /**
  2786. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2787. * @param p defines the middle point
  2788. * @param segA defines one point of the segment
  2789. * @param segB defines the other point of the segment
  2790. * @returns the shortest distance
  2791. */
  2792. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2793. var l2 = Vector2.DistanceSquared(segA, segB);
  2794. if (l2 === 0.0) {
  2795. return Vector2.Distance(p, segA);
  2796. }
  2797. var v = segB.subtract(segA);
  2798. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2799. var proj = segA.add(v.multiplyByFloats(t, t));
  2800. return Vector2.Distance(p, proj);
  2801. };
  2802. return Vector2;
  2803. }());
  2804. BABYLON.Vector2 = Vector2;
  2805. /**
  2806. * Classed used to store (x,y,z) vector representation
  2807. * A Vector3 is the main object used in 3D geometry
  2808. * It can represent etiher the coordinates of a point the space, either a direction
  2809. * Reminder: Babylon.js uses a left handed forward facing system
  2810. */
  2811. var Vector3 = /** @class */ (function () {
  2812. /**
  2813. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2814. * @param x defines the first coordinates (on X axis)
  2815. * @param y defines the second coordinates (on Y axis)
  2816. * @param z defines the third coordinates (on Z axis)
  2817. */
  2818. function Vector3(
  2819. /**
  2820. * Defines the first coordinates (on X axis)
  2821. */
  2822. x,
  2823. /**
  2824. * Defines the second coordinates (on Y axis)
  2825. */
  2826. y,
  2827. /**
  2828. * Defines the third coordinates (on Z axis)
  2829. */
  2830. z) {
  2831. if (x === void 0) { x = 0; }
  2832. if (y === void 0) { y = 0; }
  2833. if (z === void 0) { z = 0; }
  2834. this.x = x;
  2835. this.y = y;
  2836. this.z = z;
  2837. }
  2838. /**
  2839. * Creates a string representation of the Vector3
  2840. * @returns a string with the Vector3 coordinates.
  2841. */
  2842. Vector3.prototype.toString = function () {
  2843. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2844. };
  2845. /**
  2846. * Gets the class name
  2847. * @returns the string "Vector3"
  2848. */
  2849. Vector3.prototype.getClassName = function () {
  2850. return "Vector3";
  2851. };
  2852. /**
  2853. * Creates the Vector3 hash code
  2854. * @returns a number which tends to be unique between Vector3 instances
  2855. */
  2856. Vector3.prototype.getHashCode = function () {
  2857. var hash = this.x || 0;
  2858. hash = (hash * 397) ^ (this.y || 0);
  2859. hash = (hash * 397) ^ (this.z || 0);
  2860. return hash;
  2861. };
  2862. // Operators
  2863. /**
  2864. * Creates an array containing three elements : the coordinates of the Vector3
  2865. * @returns a new array of numbers
  2866. */
  2867. Vector3.prototype.asArray = function () {
  2868. var result = [];
  2869. this.toArray(result, 0);
  2870. return result;
  2871. };
  2872. /**
  2873. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2874. * @param array defines the destination array
  2875. * @param index defines the offset in the destination array
  2876. * @returns the current Vector3
  2877. */
  2878. Vector3.prototype.toArray = function (array, index) {
  2879. if (index === void 0) { index = 0; }
  2880. array[index] = this.x;
  2881. array[index + 1] = this.y;
  2882. array[index + 2] = this.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2887. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2888. */
  2889. Vector3.prototype.toQuaternion = function () {
  2890. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2891. };
  2892. /**
  2893. * Adds the given vector to the current Vector3
  2894. * @param otherVector defines the second operand
  2895. * @returns the current updated Vector3
  2896. */
  2897. Vector3.prototype.addInPlace = function (otherVector) {
  2898. this.x += otherVector.x;
  2899. this.y += otherVector.y;
  2900. this.z += otherVector.z;
  2901. return this;
  2902. };
  2903. /**
  2904. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2905. * @param otherVector defines the second operand
  2906. * @returns the resulting Vector3
  2907. */
  2908. Vector3.prototype.add = function (otherVector) {
  2909. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2910. };
  2911. /**
  2912. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2913. * @param otherVector defines the second operand
  2914. * @param result defines the Vector3 object where to store the result
  2915. * @returns the current Vector3
  2916. */
  2917. Vector3.prototype.addToRef = function (otherVector, result) {
  2918. result.x = this.x + otherVector.x;
  2919. result.y = this.y + otherVector.y;
  2920. result.z = this.z + otherVector.z;
  2921. return this;
  2922. };
  2923. /**
  2924. * Subtract the given vector from the current Vector3
  2925. * @param otherVector defines the second operand
  2926. * @returns the current updated Vector3
  2927. */
  2928. Vector3.prototype.subtractInPlace = function (otherVector) {
  2929. this.x -= otherVector.x;
  2930. this.y -= otherVector.y;
  2931. this.z -= otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the resulting Vector3
  2938. */
  2939. Vector3.prototype.subtract = function (otherVector) {
  2940. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2941. };
  2942. /**
  2943. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2944. * @param otherVector defines the second operand
  2945. * @param result defines the Vector3 object where to store the result
  2946. * @returns the current Vector3
  2947. */
  2948. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2949. result.x = this.x - otherVector.x;
  2950. result.y = this.y - otherVector.y;
  2951. result.z = this.z - otherVector.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2956. * @param x defines the x coordinate of the operand
  2957. * @param y defines the y coordinate of the operand
  2958. * @param z defines the z coordinate of the operand
  2959. * @returns the resulting Vector3
  2960. */
  2961. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2962. return new Vector3(this.x - x, this.y - y, this.z - z);
  2963. };
  2964. /**
  2965. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2966. * @param x defines the x coordinate of the operand
  2967. * @param y defines the y coordinate of the operand
  2968. * @param z defines the z coordinate of the operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2973. result.x = this.x - x;
  2974. result.y = this.y - y;
  2975. result.z = this.z - z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2980. * @returns a new Vector3
  2981. */
  2982. Vector3.prototype.negate = function () {
  2983. return new Vector3(-this.x, -this.y, -this.z);
  2984. };
  2985. /**
  2986. * Multiplies the Vector3 coordinates by the float "scale"
  2987. * @param scale defines the multiplier factor
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.scaleInPlace = function (scale) {
  2991. this.x *= scale;
  2992. this.y *= scale;
  2993. this.z *= scale;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2998. * @param scale defines the multiplier factor
  2999. * @returns a new Vector3
  3000. */
  3001. Vector3.prototype.scale = function (scale) {
  3002. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3006. * @param scale defines the multiplier factor
  3007. * @param result defines the Vector3 object where to store the result
  3008. * @returns the current Vector3
  3009. */
  3010. Vector3.prototype.scaleToRef = function (scale, result) {
  3011. result.x = this.x * scale;
  3012. result.y = this.y * scale;
  3013. result.z = this.z * scale;
  3014. return this;
  3015. };
  3016. /**
  3017. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3018. * @param scale defines the scale factor
  3019. * @param result defines the Vector3 object where to store the result
  3020. * @returns the unmodified current Vector3
  3021. */
  3022. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3023. result.x += this.x * scale;
  3024. result.y += this.y * scale;
  3025. result.z += this.z * scale;
  3026. return this;
  3027. };
  3028. /**
  3029. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3030. * @param otherVector defines the second operand
  3031. * @returns true if both vectors are equals
  3032. */
  3033. Vector3.prototype.equals = function (otherVector) {
  3034. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3035. };
  3036. /**
  3037. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3038. * @param otherVector defines the second operand
  3039. * @param epsilon defines the minimal distance to define values as equals
  3040. * @returns true if both vectors are distant less than epsilon
  3041. */
  3042. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3043. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3044. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3045. };
  3046. /**
  3047. * Returns true if the current Vector3 coordinates equals the given floats
  3048. * @param x defines the x coordinate of the operand
  3049. * @param y defines the y coordinate of the operand
  3050. * @param z defines the z coordinate of the operand
  3051. * @returns true if both vectors are equals
  3052. */
  3053. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3054. return this.x === x && this.y === y && this.z === z;
  3055. };
  3056. /**
  3057. * Multiplies the current Vector3 coordinates by the given ones
  3058. * @param otherVector defines the second operand
  3059. * @returns the current updated Vector3
  3060. */
  3061. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3062. this.x *= otherVector.x;
  3063. this.y *= otherVector.y;
  3064. this.z *= otherVector.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3069. * @param otherVector defines the second operand
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.multiply = function (otherVector) {
  3073. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3074. };
  3075. /**
  3076. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3077. * @param otherVector defines the second operand
  3078. * @param result defines the Vector3 object where to store the result
  3079. * @returns the current Vector3
  3080. */
  3081. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3082. result.x = this.x * otherVector.x;
  3083. result.y = this.y * otherVector.y;
  3084. result.z = this.z * otherVector.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3089. * @param x defines the x coordinate of the operand
  3090. * @param y defines the y coordinate of the operand
  3091. * @param z defines the z coordinate of the operand
  3092. * @returns the new Vector3
  3093. */
  3094. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3095. return new Vector3(this.x * x, this.y * y, this.z * z);
  3096. };
  3097. /**
  3098. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3099. * @param otherVector defines the second operand
  3100. * @returns the new Vector3
  3101. */
  3102. Vector3.prototype.divide = function (otherVector) {
  3103. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3104. };
  3105. /**
  3106. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3107. * @param otherVector defines the second operand
  3108. * @param result defines the Vector3 object where to store the result
  3109. * @returns the current Vector3
  3110. */
  3111. Vector3.prototype.divideToRef = function (otherVector, result) {
  3112. result.x = this.x / otherVector.x;
  3113. result.y = this.y / otherVector.y;
  3114. result.z = this.z / otherVector.z;
  3115. return this;
  3116. };
  3117. /**
  3118. * Divides the current Vector3 coordinates by the given ones.
  3119. * @param otherVector defines the second operand
  3120. * @returns the current updated Vector3
  3121. */
  3122. Vector3.prototype.divideInPlace = function (otherVector) {
  3123. return this.divideToRef(otherVector, this);
  3124. };
  3125. /**
  3126. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3127. * @param other defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.minimizeInPlace = function (other) {
  3131. if (other.x < this.x)
  3132. this.x = other.x;
  3133. if (other.y < this.y)
  3134. this.y = other.y;
  3135. if (other.z < this.z)
  3136. this.z = other.z;
  3137. return this;
  3138. };
  3139. /**
  3140. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3141. * @param other defines the second operand
  3142. * @returns the current updated Vector3
  3143. */
  3144. Vector3.prototype.maximizeInPlace = function (other) {
  3145. if (other.x > this.x)
  3146. this.x = other.x;
  3147. if (other.y > this.y)
  3148. this.y = other.y;
  3149. if (other.z > this.z)
  3150. this.z = other.z;
  3151. return this;
  3152. };
  3153. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3154. /**
  3155. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3156. */
  3157. get: function () {
  3158. var absX = Math.abs(this.x);
  3159. var absY = Math.abs(this.y);
  3160. if (absX !== absY) {
  3161. return true;
  3162. }
  3163. var absZ = Math.abs(this.z);
  3164. if (absX !== absZ) {
  3165. return true;
  3166. }
  3167. if (absY !== absZ) {
  3168. return true;
  3169. }
  3170. return false;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. /**
  3176. * Gets a new Vector3 from current Vector3 floored values
  3177. * @returns a new Vector3
  3178. */
  3179. Vector3.prototype.floor = function () {
  3180. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3181. };
  3182. /**
  3183. * Gets a new Vector3 from current Vector3 floored values
  3184. * @returns a new Vector3
  3185. */
  3186. Vector3.prototype.fract = function () {
  3187. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3188. };
  3189. // Properties
  3190. /**
  3191. * Gets the length of the Vector3
  3192. * @returns the length of the Vecto3
  3193. */
  3194. Vector3.prototype.length = function () {
  3195. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3196. };
  3197. /**
  3198. * Gets the squared length of the Vector3
  3199. * @returns squared length of the Vector3
  3200. */
  3201. Vector3.prototype.lengthSquared = function () {
  3202. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3203. };
  3204. /**
  3205. * Normalize the current Vector3.
  3206. * Please note that this is an in place operation.
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.normalize = function () {
  3210. var len = this.length();
  3211. if (len === 0 || len === 1.0)
  3212. return this;
  3213. var num = 1.0 / len;
  3214. this.x *= num;
  3215. this.y *= num;
  3216. this.z *= num;
  3217. return this;
  3218. };
  3219. /**
  3220. * Normalize the current Vector3 to a new vector
  3221. * @returns the new Vector3
  3222. */
  3223. Vector3.prototype.normalizeToNew = function () {
  3224. var normalized = new Vector3(0, 0, 0);
  3225. this.normalizeToRef(normalized);
  3226. return normalized;
  3227. };
  3228. /**
  3229. * Normalize the current Vector3 to the reference
  3230. * @param reference define the Vector3 to update
  3231. * @returns the updated Vector3
  3232. */
  3233. Vector3.prototype.normalizeToRef = function (reference) {
  3234. var len = this.length();
  3235. if (len === 0 || len === 1.0) {
  3236. reference.set(this.x, this.y, this.z);
  3237. return reference;
  3238. }
  3239. var scale = 1.0 / len;
  3240. this.scaleToRef(scale, reference);
  3241. return reference;
  3242. };
  3243. /**
  3244. * Creates a new Vector3 copied from the current Vector3
  3245. * @returns the new Vector3
  3246. */
  3247. Vector3.prototype.clone = function () {
  3248. return new Vector3(this.x, this.y, this.z);
  3249. };
  3250. /**
  3251. * Copies the given vector coordinates to the current Vector3 ones
  3252. * @param source defines the source Vector3
  3253. * @returns the current updated Vector3
  3254. */
  3255. Vector3.prototype.copyFrom = function (source) {
  3256. this.x = source.x;
  3257. this.y = source.y;
  3258. this.z = source.z;
  3259. return this;
  3260. };
  3261. /**
  3262. * Copies the given floats to the current Vector3 coordinates
  3263. * @param x defines the x coordinate of the operand
  3264. * @param y defines the y coordinate of the operand
  3265. * @param z defines the z coordinate of the operand
  3266. * @returns the current updated Vector3
  3267. */
  3268. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3269. this.x = x;
  3270. this.y = y;
  3271. this.z = z;
  3272. return this;
  3273. };
  3274. /**
  3275. * Copies the given floats to the current Vector3 coordinates
  3276. * @param x defines the x coordinate of the operand
  3277. * @param y defines the y coordinate of the operand
  3278. * @param z defines the z coordinate of the operand
  3279. * @returns the current updated Vector3
  3280. */
  3281. Vector3.prototype.set = function (x, y, z) {
  3282. return this.copyFromFloats(x, y, z);
  3283. };
  3284. // Statics
  3285. /**
  3286. * Get the clip factor between two vectors
  3287. * @param vector0 defines the first operand
  3288. * @param vector1 defines the second operand
  3289. * @param axis defines the axis to use
  3290. * @param size defines the size along the axis
  3291. * @returns the clip factor
  3292. */
  3293. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3294. var d0 = Vector3.Dot(vector0, axis) - size;
  3295. var d1 = Vector3.Dot(vector1, axis) - size;
  3296. var s = d0 / (d0 - d1);
  3297. return s;
  3298. };
  3299. /**
  3300. * Get angle between two vectors
  3301. * @param vector0 angle between vector0 and vector1
  3302. * @param vector1 angle between vector0 and vector1
  3303. * @param normal direction of the normal
  3304. * @return the angle between vector0 and vector1
  3305. */
  3306. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3307. var v0 = vector0.clone().normalize();
  3308. var v1 = vector1.clone().normalize();
  3309. var dot = Vector3.Dot(v0, v1);
  3310. var n = Vector3.Cross(v0, v1);
  3311. if (Vector3.Dot(n, normal) > 0) {
  3312. return Math.acos(dot);
  3313. }
  3314. return -Math.acos(dot);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set from the index "offset" of the given array
  3318. * @param array defines the source array
  3319. * @param offset defines the offset in the source array
  3320. * @returns the new Vector3
  3321. */
  3322. Vector3.FromArray = function (array, offset) {
  3323. if (!offset) {
  3324. offset = 0;
  3325. }
  3326. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3330. * This function is deprecated. Use FromArray instead
  3331. * @param array defines the source array
  3332. * @param offset defines the offset in the source array
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.FromFloatArray = function (array, offset) {
  3336. return Vector3.FromArray(array, offset);
  3337. };
  3338. /**
  3339. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3340. * @param array defines the source array
  3341. * @param offset defines the offset in the source array
  3342. * @param result defines the Vector3 where to store the result
  3343. */
  3344. Vector3.FromArrayToRef = function (array, offset, result) {
  3345. result.x = array[offset];
  3346. result.y = array[offset + 1];
  3347. result.z = array[offset + 2];
  3348. };
  3349. /**
  3350. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArrayToRef instead.
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @param result defines the Vector3 where to store the result
  3355. */
  3356. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3357. return Vector3.FromArrayToRef(array, offset, result);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the given floats.
  3361. * @param x defines the x coordinate of the source
  3362. * @param y defines the y coordinate of the source
  3363. * @param z defines the z coordinate of the source
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3367. result.x = x;
  3368. result.y = y;
  3369. result.z = z;
  3370. };
  3371. /**
  3372. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3373. * @returns a new empty Vector3
  3374. */
  3375. Vector3.Zero = function () {
  3376. return new Vector3(0.0, 0.0, 0.0);
  3377. };
  3378. /**
  3379. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3380. * @returns a new unit Vector3
  3381. */
  3382. Vector3.One = function () {
  3383. return new Vector3(1.0, 1.0, 1.0);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3387. * @returns a new up Vector3
  3388. */
  3389. Vector3.Up = function () {
  3390. return new Vector3(0.0, 1.0, 0.0);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3394. * @returns a new down Vector3
  3395. */
  3396. Vector3.Down = function () {
  3397. return new Vector3(0.0, -1.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3401. * @returns a new forward Vector3
  3402. */
  3403. Vector3.Forward = function () {
  3404. return new Vector3(0.0, 0.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3408. * @returns a new right Vector3
  3409. */
  3410. Vector3.Right = function () {
  3411. return new Vector3(1.0, 0.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3415. * @returns a new left Vector3
  3416. */
  3417. Vector3.Left = function () {
  3418. return new Vector3(-1.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3422. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3423. * @param vector defines the Vector3 to transform
  3424. * @param transformation defines the transformation matrix
  3425. * @returns the transformed Vector3
  3426. */
  3427. Vector3.TransformCoordinates = function (vector, transformation) {
  3428. var result = Vector3.Zero();
  3429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3430. return result;
  3431. };
  3432. /**
  3433. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3434. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3435. * @param vector defines the Vector3 to transform
  3436. * @param transformation defines the transformation matrix
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3443. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3444. result.x = x / w;
  3445. result.y = y / w;
  3446. result.z = z / w;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3450. * This method computes tranformed coordinates only, not transformed direction vectors
  3451. * @param x define the x coordinate of the source vector
  3452. * @param y define the y coordinate of the source vector
  3453. * @param z define the z coordinate of the source vector
  3454. * @param transformation defines the transformation matrix
  3455. * @param result defines the Vector3 where to store the result
  3456. */
  3457. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3458. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3459. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3460. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3461. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3462. result.x = rx / rw;
  3463. result.y = ry / rw;
  3464. result.z = rz / rw;
  3465. };
  3466. /**
  3467. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param vector defines the Vector3 to transform
  3470. * @param transformation defines the transformation matrix
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.TransformNormal = function (vector, transformation) {
  3474. var result = Vector3.Zero();
  3475. Vector3.TransformNormalToRef(vector, transformation, result);
  3476. return result;
  3477. };
  3478. /**
  3479. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3480. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3481. * @param vector defines the Vector3 to transform
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3486. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3487. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3488. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3489. result.x = x;
  3490. result.y = y;
  3491. result.z = z;
  3492. };
  3493. /**
  3494. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3495. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3496. * @param x define the x coordinate of the source vector
  3497. * @param y define the y coordinate of the source vector
  3498. * @param z define the z coordinate of the source vector
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3503. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3504. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3505. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3506. };
  3507. /**
  3508. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3509. * @param value1 defines the first control point
  3510. * @param value2 defines the second control point
  3511. * @param value3 defines the third control point
  3512. * @param value4 defines the fourth control point
  3513. * @param amount defines the amount on the spline to use
  3514. * @returns the new Vector3
  3515. */
  3516. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3517. var squared = amount * amount;
  3518. var cubed = amount * squared;
  3519. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3520. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3521. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3522. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3523. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3524. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3525. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3526. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3527. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3528. return new Vector3(x, y, z);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3532. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3533. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3534. * @param value defines the current value
  3535. * @param min defines the lower range value
  3536. * @param max defines the upper range value
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Clamp = function (value, min, max) {
  3540. var x = value.x;
  3541. x = (x > max.x) ? max.x : x;
  3542. x = (x < min.x) ? min.x : x;
  3543. var y = value.y;
  3544. y = (y > max.y) ? max.y : y;
  3545. y = (y < min.y) ? min.y : y;
  3546. var z = value.z;
  3547. z = (z > max.z) ? max.z : z;
  3548. z = (z < min.z) ? min.z : z;
  3549. return new Vector3(x, y, z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3553. * @param value1 defines the first control point
  3554. * @param tangent1 defines the first tangent vector
  3555. * @param value2 defines the second control point
  3556. * @param tangent2 defines the second tangent vector
  3557. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3561. var squared = amount * amount;
  3562. var cubed = amount * squared;
  3563. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3564. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3565. var part3 = (cubed - (2.0 * squared)) + amount;
  3566. var part4 = cubed - squared;
  3567. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3568. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3569. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3570. return new Vector3(x, y, z);
  3571. };
  3572. /**
  3573. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3574. * @param start defines the start value
  3575. * @param end defines the end value
  3576. * @param amount max defines amount between both (between 0 and 1)
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.Lerp = function (start, end, amount) {
  3580. var result = new Vector3(0, 0, 0);
  3581. Vector3.LerpToRef(start, end, amount, result);
  3582. return result;
  3583. };
  3584. /**
  3585. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3586. * @param start defines the start value
  3587. * @param end defines the end value
  3588. * @param amount max defines amount between both (between 0 and 1)
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.LerpToRef = function (start, end, amount, result) {
  3592. result.x = start.x + ((end.x - start.x) * amount);
  3593. result.y = start.y + ((end.y - start.y) * amount);
  3594. result.z = start.z + ((end.z - start.z) * amount);
  3595. };
  3596. /**
  3597. * Returns the dot product (float) between the vectors "left" and "right"
  3598. * @param left defines the left operand
  3599. * @param right defines the right operand
  3600. * @returns the dot product
  3601. */
  3602. Vector3.Dot = function (left, right) {
  3603. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3604. };
  3605. /**
  3606. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3607. * The cross product is then orthogonal to both "left" and "right"
  3608. * @param left defines the left operand
  3609. * @param right defines the right operand
  3610. * @returns the cross product
  3611. */
  3612. Vector3.Cross = function (left, right) {
  3613. var result = Vector3.Zero();
  3614. Vector3.CrossToRef(left, right, result);
  3615. return result;
  3616. };
  3617. /**
  3618. * Sets the given vector "result" with the cross product of "left" and "right"
  3619. * The cross product is then orthogonal to both "left" and "right"
  3620. * @param left defines the left operand
  3621. * @param right defines the right operand
  3622. * @param result defines the Vector3 where to store the result
  3623. */
  3624. Vector3.CrossToRef = function (left, right, result) {
  3625. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3626. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3627. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3628. result.copyFrom(MathTmp.Vector3[0]);
  3629. };
  3630. /**
  3631. * Returns a new Vector3 as the normalization of the given vector
  3632. * @param vector defines the Vector3 to normalize
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Normalize = function (vector) {
  3636. var result = Vector3.Zero();
  3637. Vector3.NormalizeToRef(vector, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the given vector "result" with the normalization of the given first vector
  3642. * @param vector defines the Vector3 to normalize
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.NormalizeToRef = function (vector, result) {
  3646. result.copyFrom(vector);
  3647. result.normalize();
  3648. };
  3649. /**
  3650. * Project a Vector3 onto screen space
  3651. * @param vector defines the Vector3 to project
  3652. * @param world defines the world matrix to use
  3653. * @param transform defines the transform (view x projection) matrix to use
  3654. * @param viewport defines the screen viewport to use
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Project = function (vector, world, transform, viewport) {
  3658. var cw = viewport.width;
  3659. var ch = viewport.height;
  3660. var cx = viewport.x;
  3661. var cy = viewport.y;
  3662. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3663. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3664. var matrix = MathTmp.Matrix[0];
  3665. world.multiplyToRef(transform, matrix);
  3666. matrix.multiplyToRef(viewportMatrix, matrix);
  3667. return Vector3.TransformCoordinates(vector, matrix);
  3668. };
  3669. /**
  3670. * Unproject from screen space to object space
  3671. * @param source defines the screen space Vector3 to use
  3672. * @param viewportWidth defines the current width of the viewport
  3673. * @param viewportHeight defines the current height of the viewport
  3674. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3675. * @param transform defines the transform (view x projection) matrix to use
  3676. * @returns the new Vector3
  3677. */
  3678. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3679. var matrix = MathTmp.Matrix[0];
  3680. world.multiplyToRef(transform, matrix);
  3681. matrix.invert();
  3682. source.x = source.x / viewportWidth * 2 - 1;
  3683. source.y = -(source.y / viewportHeight * 2 - 1);
  3684. var vector = Vector3.TransformCoordinates(source, matrix);
  3685. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3686. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3687. vector = vector.scale(1.0 / num);
  3688. }
  3689. return vector;
  3690. };
  3691. /**
  3692. * Unproject from screen space to object space
  3693. * @param source defines the screen space Vector3 to use
  3694. * @param viewportWidth defines the current width of the viewport
  3695. * @param viewportHeight defines the current height of the viewport
  3696. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3697. * @param view defines the view matrix to use
  3698. * @param projection defines the projection matrix to use
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3702. var result = Vector3.Zero();
  3703. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3704. return result;
  3705. };
  3706. /**
  3707. * Unproject from screen space to object space
  3708. * @param source defines the screen space Vector3 to use
  3709. * @param viewportWidth defines the current width of the viewport
  3710. * @param viewportHeight defines the current height of the viewport
  3711. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3712. * @param view defines the view matrix to use
  3713. * @param projection defines the projection matrix to use
  3714. * @param result defines the Vector3 where to store the result
  3715. */
  3716. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3717. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param sourceX defines the screen space x coordinate to use
  3722. * @param sourceY defines the screen space y coordinate to use
  3723. * @param sourceZ defines the screen space z coordinate to use
  3724. * @param viewportWidth defines the current width of the viewport
  3725. * @param viewportHeight defines the current height of the viewport
  3726. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3727. * @param view defines the view matrix to use
  3728. * @param projection defines the projection matrix to use
  3729. * @param result defines the Vector3 where to store the result
  3730. */
  3731. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3732. var matrix = MathTmp.Matrix[0];
  3733. world.multiplyToRef(view, matrix);
  3734. matrix.multiplyToRef(projection, matrix);
  3735. matrix.invert();
  3736. var screenSource = MathTmp.Vector3[0];
  3737. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3738. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3739. screenSource.z = 2 * sourceZ - 1.0;
  3740. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3741. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3742. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3743. result.scaleInPlace(1.0 / num);
  3744. }
  3745. };
  3746. /**
  3747. * Gets the minimal coordinate values between two Vector3
  3748. * @param left defines the first operand
  3749. * @param right defines the second operand
  3750. * @returns the new Vector3
  3751. */
  3752. Vector3.Minimize = function (left, right) {
  3753. var min = left.clone();
  3754. min.minimizeInPlace(right);
  3755. return min;
  3756. };
  3757. /**
  3758. * Gets the maximal coordinate values between two Vector3
  3759. * @param left defines the first operand
  3760. * @param right defines the second operand
  3761. * @returns the new Vector3
  3762. */
  3763. Vector3.Maximize = function (left, right) {
  3764. var max = left.clone();
  3765. max.maximizeInPlace(right);
  3766. return max;
  3767. };
  3768. /**
  3769. * Returns the distance between the vectors "value1" and "value2"
  3770. * @param value1 defines the first operand
  3771. * @param value2 defines the second operand
  3772. * @returns the distance
  3773. */
  3774. Vector3.Distance = function (value1, value2) {
  3775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3776. };
  3777. /**
  3778. * Returns the squared distance between the vectors "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the squared distance
  3782. */
  3783. Vector3.DistanceSquared = function (value1, value2) {
  3784. var x = value1.x - value2.x;
  3785. var y = value1.y - value2.y;
  3786. var z = value1.z - value2.z;
  3787. return (x * x) + (y * y) + (z * z);
  3788. };
  3789. /**
  3790. * Returns a new Vector3 located at the center between "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the new Vector3
  3794. */
  3795. Vector3.Center = function (value1, value2) {
  3796. var center = value1.add(value2);
  3797. center.scaleInPlace(0.5);
  3798. return center;
  3799. };
  3800. /**
  3801. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3802. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3803. * to something in order to rotate it from its local system to the given target system
  3804. * Note: axis1, axis2 and axis3 are normalized during this operation
  3805. * @param axis1 defines the first axis
  3806. * @param axis2 defines the second axis
  3807. * @param axis3 defines the third axis
  3808. * @returns a new Vector3
  3809. */
  3810. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3811. var rotation = Vector3.Zero();
  3812. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3813. return rotation;
  3814. };
  3815. /**
  3816. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3817. * @param axis1 defines the first axis
  3818. * @param axis2 defines the second axis
  3819. * @param axis3 defines the third axis
  3820. * @param ref defines the Vector3 where to store the result
  3821. */
  3822. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3823. var quat = MathTmp.Quaternion[0];
  3824. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3825. quat.toEulerAnglesToRef(ref);
  3826. };
  3827. return Vector3;
  3828. }());
  3829. BABYLON.Vector3 = Vector3;
  3830. //Vector4 class created for EulerAngle class conversion to Quaternion
  3831. var Vector4 = /** @class */ (function () {
  3832. /**
  3833. * Creates a Vector4 object from the given floats.
  3834. */
  3835. function Vector4(x, y, z, w) {
  3836. this.x = x;
  3837. this.y = y;
  3838. this.z = z;
  3839. this.w = w;
  3840. }
  3841. /**
  3842. * Returns the string with the Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.toString = function () {
  3845. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3846. };
  3847. /**
  3848. * Returns the string "Vector4".
  3849. */
  3850. Vector4.prototype.getClassName = function () {
  3851. return "Vector4";
  3852. };
  3853. /**
  3854. * Returns the Vector4 hash code.
  3855. */
  3856. Vector4.prototype.getHashCode = function () {
  3857. var hash = this.x || 0;
  3858. hash = (hash * 397) ^ (this.y || 0);
  3859. hash = (hash * 397) ^ (this.z || 0);
  3860. hash = (hash * 397) ^ (this.w || 0);
  3861. return hash;
  3862. };
  3863. // Operators
  3864. /**
  3865. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3866. */
  3867. Vector4.prototype.asArray = function () {
  3868. var result = new Array();
  3869. this.toArray(result, 0);
  3870. return result;
  3871. };
  3872. /**
  3873. * Populates the given array from the given index with the Vector4 coordinates.
  3874. * Returns the Vector4.
  3875. */
  3876. Vector4.prototype.toArray = function (array, index) {
  3877. if (index === undefined) {
  3878. index = 0;
  3879. }
  3880. array[index] = this.x;
  3881. array[index + 1] = this.y;
  3882. array[index + 2] = this.z;
  3883. array[index + 3] = this.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Adds the given vector to the current Vector4.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.addInPlace = function (otherVector) {
  3891. this.x += otherVector.x;
  3892. this.y += otherVector.y;
  3893. this.z += otherVector.z;
  3894. this.w += otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3899. */
  3900. Vector4.prototype.add = function (otherVector) {
  3901. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3902. };
  3903. /**
  3904. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3905. * Returns the current Vector4.
  3906. */
  3907. Vector4.prototype.addToRef = function (otherVector, result) {
  3908. result.x = this.x + otherVector.x;
  3909. result.y = this.y + otherVector.y;
  3910. result.z = this.z + otherVector.z;
  3911. result.w = this.w + otherVector.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Subtract in place the given vector from the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.subtractInPlace = function (otherVector) {
  3919. this.x -= otherVector.x;
  3920. this.y -= otherVector.y;
  3921. this.z -= otherVector.z;
  3922. this.w -= otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3927. */
  3928. Vector4.prototype.subtract = function (otherVector) {
  3929. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3930. };
  3931. /**
  3932. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3936. result.x = this.x - otherVector.x;
  3937. result.y = this.y - otherVector.y;
  3938. result.z = this.z - otherVector.z;
  3939. result.w = this.w - otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3946. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3947. };
  3948. /**
  3949. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3950. * Returns the current Vector4.
  3951. */
  3952. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3953. result.x = this.x - x;
  3954. result.y = this.y - y;
  3955. result.z = this.z - z;
  3956. result.w = this.w - w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3961. */
  3962. Vector4.prototype.negate = function () {
  3963. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3964. };
  3965. /**
  3966. * Multiplies the current Vector4 coordinates by scale (float).
  3967. * Returns the updated Vector4.
  3968. */
  3969. Vector4.prototype.scaleInPlace = function (scale) {
  3970. this.x *= scale;
  3971. this.y *= scale;
  3972. this.z *= scale;
  3973. this.w *= scale;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3978. */
  3979. Vector4.prototype.scale = function (scale) {
  3980. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3981. };
  3982. /**
  3983. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3984. * Returns the current Vector4.
  3985. */
  3986. Vector4.prototype.scaleToRef = function (scale, result) {
  3987. result.x = this.x * scale;
  3988. result.y = this.y * scale;
  3989. result.z = this.z * scale;
  3990. result.w = this.w * scale;
  3991. return this;
  3992. };
  3993. /**
  3994. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3995. * @param scale defines the scale factor
  3996. * @param result defines the Vector4 object where to store the result
  3997. * @returns the unmodified current Vector4
  3998. */
  3999. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4000. result.x += this.x * scale;
  4001. result.y += this.y * scale;
  4002. result.z += this.z * scale;
  4003. result.w += this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4008. */
  4009. Vector4.prototype.equals = function (otherVector) {
  4010. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4011. };
  4012. /**
  4013. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4014. */
  4015. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4017. return otherVector
  4018. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4019. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4020. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4021. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4022. };
  4023. /**
  4024. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4025. */
  4026. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4027. return this.x === x && this.y === y && this.z === z && this.w === w;
  4028. };
  4029. /**
  4030. * Multiplies in place the current Vector4 by the given one.
  4031. * Returns the updated Vector4.
  4032. */
  4033. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4034. this.x *= otherVector.x;
  4035. this.y *= otherVector.y;
  4036. this.z *= otherVector.z;
  4037. this.w *= otherVector.w;
  4038. return this;
  4039. };
  4040. /**
  4041. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4042. */
  4043. Vector4.prototype.multiply = function (otherVector) {
  4044. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4045. };
  4046. /**
  4047. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4048. * Returns the current Vector4.
  4049. */
  4050. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4051. result.x = this.x * otherVector.x;
  4052. result.y = this.y * otherVector.y;
  4053. result.z = this.z * otherVector.z;
  4054. result.w = this.w * otherVector.w;
  4055. return this;
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4059. */
  4060. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4061. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4065. */
  4066. Vector4.prototype.divide = function (otherVector) {
  4067. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4068. };
  4069. /**
  4070. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4071. * Returns the current Vector4.
  4072. */
  4073. Vector4.prototype.divideToRef = function (otherVector, result) {
  4074. result.x = this.x / otherVector.x;
  4075. result.y = this.y / otherVector.y;
  4076. result.z = this.z / otherVector.z;
  4077. result.w = this.w / otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Divides the current Vector3 coordinates by the given ones.
  4082. * @returns the updated Vector3.
  4083. */
  4084. Vector4.prototype.divideInPlace = function (otherVector) {
  4085. return this.divideToRef(otherVector, this);
  4086. };
  4087. /**
  4088. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4089. * @param other defines the second operand
  4090. * @returns the current updated Vector4
  4091. */
  4092. Vector4.prototype.minimizeInPlace = function (other) {
  4093. if (other.x < this.x)
  4094. this.x = other.x;
  4095. if (other.y < this.y)
  4096. this.y = other.y;
  4097. if (other.z < this.z)
  4098. this.z = other.z;
  4099. if (other.w < this.w)
  4100. this.w = other.w;
  4101. return this;
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.maximizeInPlace = function (other) {
  4109. if (other.x > this.x)
  4110. this.x = other.x;
  4111. if (other.y > this.y)
  4112. this.y = other.y;
  4113. if (other.z > this.z)
  4114. this.z = other.z;
  4115. if (other.w > this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Gets a new Vector4 from current Vector4 floored values
  4121. * @returns a new Vector4
  4122. */
  4123. Vector4.prototype.floor = function () {
  4124. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4125. };
  4126. /**
  4127. * Gets a new Vector4 from current Vector3 floored values
  4128. * @returns a new Vector4
  4129. */
  4130. Vector4.prototype.fract = function () {
  4131. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4132. };
  4133. // Properties
  4134. /**
  4135. * Returns the Vector4 length (float).
  4136. */
  4137. Vector4.prototype.length = function () {
  4138. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. /**
  4141. * Returns the Vector4 squared length (float).
  4142. */
  4143. Vector4.prototype.lengthSquared = function () {
  4144. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4145. };
  4146. // Methods
  4147. /**
  4148. * Normalizes in place the Vector4.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.normalize = function () {
  4152. var len = this.length();
  4153. if (len === 0)
  4154. return this;
  4155. var num = 1.0 / len;
  4156. this.x *= num;
  4157. this.y *= num;
  4158. this.z *= num;
  4159. this.w *= num;
  4160. return this;
  4161. };
  4162. /**
  4163. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4164. */
  4165. Vector4.prototype.toVector3 = function () {
  4166. return new Vector3(this.x, this.y, this.z);
  4167. };
  4168. /**
  4169. * Returns a new Vector4 copied from the current one.
  4170. */
  4171. Vector4.prototype.clone = function () {
  4172. return new Vector4(this.x, this.y, this.z, this.w);
  4173. };
  4174. /**
  4175. * Updates the current Vector4 with the given one coordinates.
  4176. * Returns the updated Vector4.
  4177. */
  4178. Vector4.prototype.copyFrom = function (source) {
  4179. this.x = source.x;
  4180. this.y = source.y;
  4181. this.z = source.z;
  4182. this.w = source.w;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates the current Vector4 coordinates with the given floats.
  4187. * Returns the updated Vector4.
  4188. */
  4189. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4190. this.x = x;
  4191. this.y = y;
  4192. this.z = z;
  4193. this.w = w;
  4194. return this;
  4195. };
  4196. /**
  4197. * Updates the current Vector4 coordinates with the given floats.
  4198. * Returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.set = function (x, y, z, w) {
  4201. return this.copyFromFloats(x, y, z, w);
  4202. };
  4203. // Statics
  4204. /**
  4205. * Returns a new Vector4 set from the starting index of the given array.
  4206. */
  4207. Vector4.FromArray = function (array, offset) {
  4208. if (!offset) {
  4209. offset = 0;
  4210. }
  4211. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4212. };
  4213. /**
  4214. * Updates the given vector "result" from the starting index of the given array.
  4215. */
  4216. Vector4.FromArrayToRef = function (array, offset, result) {
  4217. result.x = array[offset];
  4218. result.y = array[offset + 1];
  4219. result.z = array[offset + 2];
  4220. result.w = array[offset + 3];
  4221. };
  4222. /**
  4223. * Updates the given vector "result" from the starting index of the given Float32Array.
  4224. */
  4225. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4226. Vector4.FromArrayToRef(array, offset, result);
  4227. };
  4228. /**
  4229. * Updates the given vector "result" coordinates from the given floats.
  4230. */
  4231. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4232. result.x = x;
  4233. result.y = y;
  4234. result.z = z;
  4235. result.w = w;
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4239. */
  4240. Vector4.Zero = function () {
  4241. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4242. };
  4243. /**
  4244. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4245. */
  4246. Vector4.One = function () {
  4247. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4248. };
  4249. /**
  4250. * Returns a new normalized Vector4 from the given one.
  4251. */
  4252. Vector4.Normalize = function (vector) {
  4253. var result = Vector4.Zero();
  4254. Vector4.NormalizeToRef(vector, result);
  4255. return result;
  4256. };
  4257. /**
  4258. * Updates the given vector "result" from the normalization of the given one.
  4259. */
  4260. Vector4.NormalizeToRef = function (vector, result) {
  4261. result.copyFrom(vector);
  4262. result.normalize();
  4263. };
  4264. Vector4.Minimize = function (left, right) {
  4265. var min = left.clone();
  4266. min.minimizeInPlace(right);
  4267. return min;
  4268. };
  4269. Vector4.Maximize = function (left, right) {
  4270. var max = left.clone();
  4271. max.maximizeInPlace(right);
  4272. return max;
  4273. };
  4274. /**
  4275. * Returns the distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.Distance = function (value1, value2) {
  4278. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4279. };
  4280. /**
  4281. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4282. */
  4283. Vector4.DistanceSquared = function (value1, value2) {
  4284. var x = value1.x - value2.x;
  4285. var y = value1.y - value2.y;
  4286. var z = value1.z - value2.z;
  4287. var w = value1.w - value2.w;
  4288. return (x * x) + (y * y) + (z * z) + (w * w);
  4289. };
  4290. /**
  4291. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4292. */
  4293. Vector4.Center = function (value1, value2) {
  4294. var center = value1.add(value2);
  4295. center.scaleInPlace(0.5);
  4296. return center;
  4297. };
  4298. /**
  4299. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4300. * This methods computes transformed normalized direction vectors only.
  4301. */
  4302. Vector4.TransformNormal = function (vector, transformation) {
  4303. var result = Vector4.Zero();
  4304. Vector4.TransformNormalToRef(vector, transformation, result);
  4305. return result;
  4306. };
  4307. /**
  4308. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4309. * This methods computes transformed normalized direction vectors only.
  4310. */
  4311. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4312. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4313. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4314. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4315. result.x = x;
  4316. result.y = y;
  4317. result.z = z;
  4318. result.w = vector.w;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4325. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4326. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4327. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4328. result.w = w;
  4329. };
  4330. return Vector4;
  4331. }());
  4332. BABYLON.Vector4 = Vector4;
  4333. var Size = /** @class */ (function () {
  4334. /**
  4335. * Creates a Size object from the given width and height (floats).
  4336. */
  4337. function Size(width, height) {
  4338. this.width = width;
  4339. this.height = height;
  4340. }
  4341. // Returns a string with the Size width and height.
  4342. Size.prototype.toString = function () {
  4343. return "{W: " + this.width + ", H: " + this.height + "}";
  4344. };
  4345. /**
  4346. * Returns the string "Size"
  4347. */
  4348. Size.prototype.getClassName = function () {
  4349. return "Size";
  4350. };
  4351. /**
  4352. * Returns the Size hash code.
  4353. */
  4354. Size.prototype.getHashCode = function () {
  4355. var hash = this.width || 0;
  4356. hash = (hash * 397) ^ (this.height || 0);
  4357. return hash;
  4358. };
  4359. /**
  4360. * Updates the current size from the given one.
  4361. * Returns the updated Size.
  4362. */
  4363. Size.prototype.copyFrom = function (src) {
  4364. this.width = src.width;
  4365. this.height = src.height;
  4366. };
  4367. /**
  4368. * Updates in place the current Size from the given floats.
  4369. * Returns the updated Size.
  4370. */
  4371. Size.prototype.copyFromFloats = function (width, height) {
  4372. this.width = width;
  4373. this.height = height;
  4374. return this;
  4375. };
  4376. /**
  4377. * Updates in place the current Size from the given floats.
  4378. * Returns the updated Size.
  4379. */
  4380. Size.prototype.set = function (width, height) {
  4381. return this.copyFromFloats(width, height);
  4382. };
  4383. /**
  4384. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4385. */
  4386. Size.prototype.multiplyByFloats = function (w, h) {
  4387. return new Size(this.width * w, this.height * h);
  4388. };
  4389. /**
  4390. * Returns a new Size copied from the given one.
  4391. */
  4392. Size.prototype.clone = function () {
  4393. return new Size(this.width, this.height);
  4394. };
  4395. /**
  4396. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4397. */
  4398. Size.prototype.equals = function (other) {
  4399. if (!other) {
  4400. return false;
  4401. }
  4402. return (this.width === other.width) && (this.height === other.height);
  4403. };
  4404. Object.defineProperty(Size.prototype, "surface", {
  4405. /**
  4406. * Returns the surface of the Size : width * height (float).
  4407. */
  4408. get: function () {
  4409. return this.width * this.height;
  4410. },
  4411. enumerable: true,
  4412. configurable: true
  4413. });
  4414. /**
  4415. * Returns a new Size set to (0.0, 0.0)
  4416. */
  4417. Size.Zero = function () {
  4418. return new Size(0.0, 0.0);
  4419. };
  4420. /**
  4421. * Returns a new Size set as the addition result of the current Size and the given one.
  4422. */
  4423. Size.prototype.add = function (otherSize) {
  4424. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4425. return r;
  4426. };
  4427. /**
  4428. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4429. */
  4430. Size.prototype.subtract = function (otherSize) {
  4431. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4432. return r;
  4433. };
  4434. /**
  4435. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4436. */
  4437. Size.Lerp = function (start, end, amount) {
  4438. var w = start.width + ((end.width - start.width) * amount);
  4439. var h = start.height + ((end.height - start.height) * amount);
  4440. return new Size(w, h);
  4441. };
  4442. return Size;
  4443. }());
  4444. BABYLON.Size = Size;
  4445. /**
  4446. * Class used to store quaternion data
  4447. * @see https://en.wikipedia.org/wiki/Quaternion
  4448. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4449. */
  4450. var Quaternion = /** @class */ (function () {
  4451. /**
  4452. * Creates a new Quaternion from the given floats
  4453. * @param x defines the first component (0 by default)
  4454. * @param y defines the second component (0 by default)
  4455. * @param z defines the third component (0 by default)
  4456. * @param w defines the fourth component (1.0 by default)
  4457. */
  4458. function Quaternion(
  4459. /** defines the first component (0 by default) */
  4460. x,
  4461. /** defines the second component (0 by default) */
  4462. y,
  4463. /** defines the third component (0 by default) */
  4464. z,
  4465. /** defines the fourth component (1.0 by default) */
  4466. w) {
  4467. if (x === void 0) { x = 0.0; }
  4468. if (y === void 0) { y = 0.0; }
  4469. if (z === void 0) { z = 0.0; }
  4470. if (w === void 0) { w = 1.0; }
  4471. this.x = x;
  4472. this.y = y;
  4473. this.z = z;
  4474. this.w = w;
  4475. }
  4476. /**
  4477. * Gets a string representation for the current quaternion
  4478. * @returns a string with the Quaternion coordinates
  4479. */
  4480. Quaternion.prototype.toString = function () {
  4481. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4482. };
  4483. /**
  4484. * Gets the class name of the quaternion
  4485. * @returns the string "Quaternion"
  4486. */
  4487. Quaternion.prototype.getClassName = function () {
  4488. return "Quaternion";
  4489. };
  4490. /**
  4491. * Gets a hash code for this quaternion
  4492. * @returns the quaternion hash code
  4493. */
  4494. Quaternion.prototype.getHashCode = function () {
  4495. var hash = this.x || 0;
  4496. hash = (hash * 397) ^ (this.y || 0);
  4497. hash = (hash * 397) ^ (this.z || 0);
  4498. hash = (hash * 397) ^ (this.w || 0);
  4499. return hash;
  4500. };
  4501. /**
  4502. * Copy the quaternion to an array
  4503. * @returns a new array populated with 4 elements from the quaternion coordinates
  4504. */
  4505. Quaternion.prototype.asArray = function () {
  4506. return [this.x, this.y, this.z, this.w];
  4507. };
  4508. /**
  4509. * Check if two quaternions are equals
  4510. * @param otherQuaternion defines the second operand
  4511. * @return true if the current quaternion and the given one coordinates are strictly equals
  4512. */
  4513. Quaternion.prototype.equals = function (otherQuaternion) {
  4514. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4515. };
  4516. /**
  4517. * Clone the current quaternion
  4518. * @returns a new quaternion copied from the current one
  4519. */
  4520. Quaternion.prototype.clone = function () {
  4521. return new Quaternion(this.x, this.y, this.z, this.w);
  4522. };
  4523. /**
  4524. * Copy a quaternion to the current one
  4525. * @param other defines the other quaternion
  4526. * @returns the updated current quaternion
  4527. */
  4528. Quaternion.prototype.copyFrom = function (other) {
  4529. this.x = other.x;
  4530. this.y = other.y;
  4531. this.z = other.z;
  4532. this.w = other.w;
  4533. return this;
  4534. };
  4535. /**
  4536. * Updates the current quaternion with the given float coordinates
  4537. * @param x defines the x coordinate
  4538. * @param y defines the y coordinate
  4539. * @param z defines the z coordinate
  4540. * @param w defines the w coordinate
  4541. * @returns the updated current quaternion
  4542. */
  4543. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4544. this.x = x;
  4545. this.y = y;
  4546. this.z = z;
  4547. this.w = w;
  4548. return this;
  4549. };
  4550. /**
  4551. * Updates the current quaternion from the given float coordinates
  4552. * @param x defines the x coordinate
  4553. * @param y defines the y coordinate
  4554. * @param z defines the z coordinate
  4555. * @param w defines the w coordinate
  4556. * @returns the updated current quaternion
  4557. */
  4558. Quaternion.prototype.set = function (x, y, z, w) {
  4559. return this.copyFromFloats(x, y, z, w);
  4560. };
  4561. /**
  4562. * Adds two quaternions
  4563. * @param other defines the second operand
  4564. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4565. */
  4566. Quaternion.prototype.add = function (other) {
  4567. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4568. };
  4569. /**
  4570. * Add a quaternion to the current one
  4571. * @param other defines the quaternion to add
  4572. * @returns the current quaternion
  4573. */
  4574. Quaternion.prototype.addInPlace = function (other) {
  4575. this.x += other.x;
  4576. this.y += other.y;
  4577. this.z += other.z;
  4578. this.w += other.w;
  4579. return this;
  4580. };
  4581. /**
  4582. * Subtract two quaternions
  4583. * @param other defines the second operand
  4584. * @returns a new quaternion as the subtraction result of the given one from the current one
  4585. */
  4586. Quaternion.prototype.subtract = function (other) {
  4587. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4588. };
  4589. /**
  4590. * Multiplies the current quaternion by a scale factor
  4591. * @param value defines the scale factor
  4592. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4593. */
  4594. Quaternion.prototype.scale = function (value) {
  4595. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4596. };
  4597. /**
  4598. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4599. * @param scale defines the scale factor
  4600. * @param result defines the Quaternion object where to store the result
  4601. * @returns the unmodified current quaternion
  4602. */
  4603. Quaternion.prototype.scaleToRef = function (scale, result) {
  4604. result.x = this.x * scale;
  4605. result.y = this.y * scale;
  4606. result.z = this.z * scale;
  4607. result.w = this.w * scale;
  4608. return this;
  4609. };
  4610. /**
  4611. * Multiplies in place the current quaternion by a scale factor
  4612. * @param value defines the scale factor
  4613. * @returns the current modified quaternion
  4614. */
  4615. Quaternion.prototype.scaleInPlace = function (value) {
  4616. this.x *= value;
  4617. this.y *= value;
  4618. this.z *= value;
  4619. this.w *= value;
  4620. return this;
  4621. };
  4622. /**
  4623. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4624. * @param scale defines the scale factor
  4625. * @param result defines the Quaternion object where to store the result
  4626. * @returns the unmodified current quaternion
  4627. */
  4628. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4629. result.x += this.x * scale;
  4630. result.y += this.y * scale;
  4631. result.z += this.z * scale;
  4632. result.w += this.w * scale;
  4633. return this;
  4634. };
  4635. /**
  4636. * Multiplies two quaternions
  4637. * @param q1 defines the second operand
  4638. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4639. */
  4640. Quaternion.prototype.multiply = function (q1) {
  4641. var result = new Quaternion(0, 0, 0, 1.0);
  4642. this.multiplyToRef(q1, result);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4647. * @param q1 defines the second operand
  4648. * @param result defines the target quaternion
  4649. * @returns the current quaternion
  4650. */
  4651. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4652. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4653. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4654. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4655. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4656. result.copyFromFloats(x, y, z, w);
  4657. return this;
  4658. };
  4659. /**
  4660. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @returns the currentupdated quaternion
  4663. */
  4664. Quaternion.prototype.multiplyInPlace = function (q1) {
  4665. this.multiplyToRef(q1, this);
  4666. return this;
  4667. };
  4668. /**
  4669. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4670. * @param ref defines the target quaternion
  4671. * @returns the current quaternion
  4672. */
  4673. Quaternion.prototype.conjugateToRef = function (ref) {
  4674. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4675. return this;
  4676. };
  4677. /**
  4678. * Conjugates in place (1-q) the current quaternion
  4679. * @returns the current updated quaternion
  4680. */
  4681. Quaternion.prototype.conjugateInPlace = function () {
  4682. this.x *= -1;
  4683. this.y *= -1;
  4684. this.z *= -1;
  4685. return this;
  4686. };
  4687. /**
  4688. * Conjugates in place (1-q) the current quaternion
  4689. * @returns a new quaternion
  4690. */
  4691. Quaternion.prototype.conjugate = function () {
  4692. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4693. return result;
  4694. };
  4695. /**
  4696. * Gets length of current quaternion
  4697. * @returns the quaternion length (float)
  4698. */
  4699. Quaternion.prototype.length = function () {
  4700. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4701. };
  4702. /**
  4703. * Normalize in place the current quaternion
  4704. * @returns the current updated quaternion
  4705. */
  4706. Quaternion.prototype.normalize = function () {
  4707. var length = 1.0 / this.length();
  4708. this.x *= length;
  4709. this.y *= length;
  4710. this.z *= length;
  4711. this.w *= length;
  4712. return this;
  4713. };
  4714. /**
  4715. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4716. * @param order is a reserved parameter and is ignore for now
  4717. * @returns a new Vector3 containing the Euler angles
  4718. */
  4719. Quaternion.prototype.toEulerAngles = function (order) {
  4720. if (order === void 0) { order = "YZX"; }
  4721. var result = Vector3.Zero();
  4722. this.toEulerAnglesToRef(result, order);
  4723. return result;
  4724. };
  4725. /**
  4726. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4727. * @param result defines the vector which will be filled with the Euler angles
  4728. * @param order is a reserved parameter and is ignore for now
  4729. * @returns the current unchanged quaternion
  4730. */
  4731. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4732. if (order === void 0) { order = "YZX"; }
  4733. var qz = this.z;
  4734. var qx = this.x;
  4735. var qy = this.y;
  4736. var qw = this.w;
  4737. var sqw = qw * qw;
  4738. var sqz = qz * qz;
  4739. var sqx = qx * qx;
  4740. var sqy = qy * qy;
  4741. var zAxisY = qy * qz - qx * qw;
  4742. var limit = .4999999;
  4743. if (zAxisY < -limit) {
  4744. result.y = 2 * Math.atan2(qy, qw);
  4745. result.x = Math.PI / 2;
  4746. result.z = 0;
  4747. }
  4748. else if (zAxisY > limit) {
  4749. result.y = 2 * Math.atan2(qy, qw);
  4750. result.x = -Math.PI / 2;
  4751. result.z = 0;
  4752. }
  4753. else {
  4754. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4755. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4756. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4757. }
  4758. return this;
  4759. };
  4760. /**
  4761. * Updates the given rotation matrix with the current quaternion values
  4762. * @param result defines the target matrix
  4763. * @returns the current unchanged quaternion
  4764. */
  4765. Quaternion.prototype.toRotationMatrix = function (result) {
  4766. var xx = this.x * this.x;
  4767. var yy = this.y * this.y;
  4768. var zz = this.z * this.z;
  4769. var xy = this.x * this.y;
  4770. var zw = this.z * this.w;
  4771. var zx = this.z * this.x;
  4772. var yw = this.y * this.w;
  4773. var yz = this.y * this.z;
  4774. var xw = this.x * this.w;
  4775. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4776. result.m[1] = 2.0 * (xy + zw);
  4777. result.m[2] = 2.0 * (zx - yw);
  4778. result.m[3] = 0;
  4779. result.m[4] = 2.0 * (xy - zw);
  4780. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4781. result.m[6] = 2.0 * (yz + xw);
  4782. result.m[7] = 0;
  4783. result.m[8] = 2.0 * (zx + yw);
  4784. result.m[9] = 2.0 * (yz - xw);
  4785. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4786. result.m[11] = 0;
  4787. result.m[12] = 0;
  4788. result.m[13] = 0;
  4789. result.m[14] = 0;
  4790. result.m[15] = 1.0;
  4791. result._markAsUpdated();
  4792. return this;
  4793. };
  4794. /**
  4795. * Updates the current quaternion from the given rotation matrix values
  4796. * @param matrix defines the source matrix
  4797. * @returns the current updated quaternion
  4798. */
  4799. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4800. Quaternion.FromRotationMatrixToRef(matrix, this);
  4801. return this;
  4802. };
  4803. // Statics
  4804. /**
  4805. * Creates a new quaternion from a rotation matrix
  4806. * @param matrix defines the source matrix
  4807. * @returns a new quaternion created from the given rotation matrix values
  4808. */
  4809. Quaternion.FromRotationMatrix = function (matrix) {
  4810. var result = new Quaternion();
  4811. Quaternion.FromRotationMatrixToRef(matrix, result);
  4812. return result;
  4813. };
  4814. /**
  4815. * Updates the given quaternion with the given rotation matrix values
  4816. * @param matrix defines the source matrix
  4817. * @param result defines the target quaternion
  4818. */
  4819. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4820. var data = matrix.m;
  4821. var m11 = data[0], m12 = data[4], m13 = data[8];
  4822. var m21 = data[1], m22 = data[5], m23 = data[9];
  4823. var m31 = data[2], m32 = data[6], m33 = data[10];
  4824. var trace = m11 + m22 + m33;
  4825. var s;
  4826. if (trace > 0) {
  4827. s = 0.5 / Math.sqrt(trace + 1.0);
  4828. result.w = 0.25 / s;
  4829. result.x = (m32 - m23) * s;
  4830. result.y = (m13 - m31) * s;
  4831. result.z = (m21 - m12) * s;
  4832. }
  4833. else if (m11 > m22 && m11 > m33) {
  4834. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4835. result.w = (m32 - m23) / s;
  4836. result.x = 0.25 * s;
  4837. result.y = (m12 + m21) / s;
  4838. result.z = (m13 + m31) / s;
  4839. }
  4840. else if (m22 > m33) {
  4841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4842. result.w = (m13 - m31) / s;
  4843. result.x = (m12 + m21) / s;
  4844. result.y = 0.25 * s;
  4845. result.z = (m23 + m32) / s;
  4846. }
  4847. else {
  4848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4849. result.w = (m21 - m12) / s;
  4850. result.x = (m13 + m31) / s;
  4851. result.y = (m23 + m32) / s;
  4852. result.z = 0.25 * s;
  4853. }
  4854. };
  4855. /**
  4856. * Returns the dot product (float) between the quaternions "left" and "right"
  4857. * @param left defines the left operand
  4858. * @param right defines the right operand
  4859. * @returns the dot product
  4860. */
  4861. Quaternion.Dot = function (left, right) {
  4862. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4863. };
  4864. /**
  4865. * Checks if the two quaternions are close to each other
  4866. * @param quat0 defines the first quaternion to check
  4867. * @param quat1 defines the second quaternion to check
  4868. * @returns true if the two quaternions are close to each other
  4869. */
  4870. Quaternion.AreClose = function (quat0, quat1) {
  4871. var dot = Quaternion.Dot(quat0, quat1);
  4872. return dot >= 0;
  4873. };
  4874. /**
  4875. * Creates an empty quaternion
  4876. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4877. */
  4878. Quaternion.Zero = function () {
  4879. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4880. };
  4881. /**
  4882. * Inverse a given quaternion
  4883. * @param q defines the source quaternion
  4884. * @returns a new quaternion as the inverted current quaternion
  4885. */
  4886. Quaternion.Inverse = function (q) {
  4887. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4888. };
  4889. /**
  4890. * Creates an identity quaternion
  4891. * @returns the identity quaternion
  4892. */
  4893. Quaternion.Identity = function () {
  4894. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4895. };
  4896. /**
  4897. * Gets a boolean indicating if the given quaternion is identity
  4898. * @param quaternion defines the quaternion to check
  4899. * @returns true if the quaternion is identity
  4900. */
  4901. Quaternion.IsIdentity = function (quaternion) {
  4902. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4903. };
  4904. /**
  4905. * Creates a quaternion from a rotation around an axis
  4906. * @param axis defines the axis to use
  4907. * @param angle defines the angle to use
  4908. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4909. */
  4910. Quaternion.RotationAxis = function (axis, angle) {
  4911. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4912. };
  4913. /**
  4914. * Creates a rotation around an axis and stores it into the given quaternion
  4915. * @param axis defines the axis to use
  4916. * @param angle defines the angle to use
  4917. * @param result defines the target quaternion
  4918. * @returns the target quaternion
  4919. */
  4920. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4921. var sin = Math.sin(angle / 2);
  4922. axis.normalize();
  4923. result.w = Math.cos(angle / 2);
  4924. result.x = axis.x * sin;
  4925. result.y = axis.y * sin;
  4926. result.z = axis.z * sin;
  4927. return result;
  4928. };
  4929. /**
  4930. * Creates a new quaternion from data stored into an array
  4931. * @param array defines the data source
  4932. * @param offset defines the offset in the source array where the data starts
  4933. * @returns a new quaternion
  4934. */
  4935. Quaternion.FromArray = function (array, offset) {
  4936. if (!offset) {
  4937. offset = 0;
  4938. }
  4939. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4940. };
  4941. /**
  4942. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4943. * @param yaw defines the rotation around Y axis
  4944. * @param pitch defines the rotation around X axis
  4945. * @param roll defines the rotation around Z axis
  4946. * @returns the new quaternion
  4947. */
  4948. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4949. var q = new Quaternion();
  4950. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4951. return q;
  4952. };
  4953. /**
  4954. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4955. * @param yaw defines the rotation around Y axis
  4956. * @param pitch defines the rotation around X axis
  4957. * @param roll defines the rotation around Z axis
  4958. * @param result defines the target quaternion
  4959. */
  4960. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4961. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4962. var halfRoll = roll * 0.5;
  4963. var halfPitch = pitch * 0.5;
  4964. var halfYaw = yaw * 0.5;
  4965. var sinRoll = Math.sin(halfRoll);
  4966. var cosRoll = Math.cos(halfRoll);
  4967. var sinPitch = Math.sin(halfPitch);
  4968. var cosPitch = Math.cos(halfPitch);
  4969. var sinYaw = Math.sin(halfYaw);
  4970. var cosYaw = Math.cos(halfYaw);
  4971. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4972. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4973. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4974. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4975. };
  4976. /**
  4977. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4978. * @param alpha defines the rotation around first axis
  4979. * @param beta defines the rotation around second axis
  4980. * @param gamma defines the rotation around third axis
  4981. * @returns the new quaternion
  4982. */
  4983. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4984. var result = new Quaternion();
  4985. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4986. return result;
  4987. };
  4988. /**
  4989. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4990. * @param alpha defines the rotation around first axis
  4991. * @param beta defines the rotation around second axis
  4992. * @param gamma defines the rotation around third axis
  4993. * @param result defines the target quaternion
  4994. */
  4995. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4996. // Produces a quaternion from Euler angles in the z-x-z orientation
  4997. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4998. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4999. var halfBeta = beta * 0.5;
  5000. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5001. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5002. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5003. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5004. };
  5005. /**
  5006. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5007. * @param axis1 defines the first axis
  5008. * @param axis2 defines the second axis
  5009. * @param axis3 defines the third axis
  5010. * @returns the new quaternion
  5011. */
  5012. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5013. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5014. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5015. return quat;
  5016. };
  5017. /**
  5018. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5019. * @param axis1 defines the first axis
  5020. * @param axis2 defines the second axis
  5021. * @param axis3 defines the third axis
  5022. * @param ref defines the target quaternion
  5023. */
  5024. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5025. var rotMat = MathTmp.Matrix[0];
  5026. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5027. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5028. };
  5029. /**
  5030. * Interpolates between two quaternions
  5031. * @param left defines first quaternion
  5032. * @param right defines second quaternion
  5033. * @param amount defines the gradient to use
  5034. * @returns the new interpolated quaternion
  5035. */
  5036. Quaternion.Slerp = function (left, right, amount) {
  5037. var result = Quaternion.Identity();
  5038. Quaternion.SlerpToRef(left, right, amount, result);
  5039. return result;
  5040. };
  5041. /**
  5042. * Interpolates between two quaternions and stores it into a target quaternion
  5043. * @param left defines first quaternion
  5044. * @param right defines second quaternion
  5045. * @param amount defines the gradient to use
  5046. * @param result defines the target quaternion
  5047. */
  5048. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5049. var num2;
  5050. var num3;
  5051. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5052. var flag = false;
  5053. if (num4 < 0) {
  5054. flag = true;
  5055. num4 = -num4;
  5056. }
  5057. if (num4 > 0.999999) {
  5058. num3 = 1 - amount;
  5059. num2 = flag ? -amount : amount;
  5060. }
  5061. else {
  5062. var num5 = Math.acos(num4);
  5063. var num6 = (1.0 / Math.sin(num5));
  5064. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5065. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5066. }
  5067. result.x = (num3 * left.x) + (num2 * right.x);
  5068. result.y = (num3 * left.y) + (num2 * right.y);
  5069. result.z = (num3 * left.z) + (num2 * right.z);
  5070. result.w = (num3 * left.w) + (num2 * right.w);
  5071. };
  5072. /**
  5073. * Interpolate between two quaternions using Hermite interpolation
  5074. * @param value1 defines first quaternion
  5075. * @param tangent1 defines the incoming tangent
  5076. * @param value2 defines second quaternion
  5077. * @param tangent2 defines the outgoing tangent
  5078. * @param amount defines the target quaternion
  5079. * @returns the new interpolated quaternion
  5080. */
  5081. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5082. var squared = amount * amount;
  5083. var cubed = amount * squared;
  5084. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5085. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5086. var part3 = (cubed - (2.0 * squared)) + amount;
  5087. var part4 = cubed - squared;
  5088. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5089. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5090. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5091. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5092. return new Quaternion(x, y, z, w);
  5093. };
  5094. return Quaternion;
  5095. }());
  5096. BABYLON.Quaternion = Quaternion;
  5097. /**
  5098. * Class used to store matrix data (4x4)
  5099. */
  5100. var Matrix = /** @class */ (function () {
  5101. /**
  5102. * Creates an empty matrix (filled with zeros)
  5103. */
  5104. function Matrix() {
  5105. this._isIdentity = false;
  5106. this._isIdentityDirty = true;
  5107. /**
  5108. * Gets or sets the internal data of the matrix
  5109. */
  5110. this.m = new Float32Array(16);
  5111. this._markAsUpdated();
  5112. }
  5113. /** @hidden */
  5114. Matrix.prototype._markAsUpdated = function () {
  5115. this.updateFlag = Matrix._updateFlagSeed++;
  5116. this._isIdentityDirty = true;
  5117. };
  5118. // Properties
  5119. /**
  5120. * Check if the current matrix is indentity
  5121. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5122. * @returns true is the matrix is the identity matrix
  5123. */
  5124. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5125. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5126. if (this._isIdentityDirty) {
  5127. this._isIdentityDirty = false;
  5128. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5132. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5133. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5134. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. else {
  5138. this._isIdentity = true;
  5139. }
  5140. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5141. this._isIdentity = false;
  5142. }
  5143. }
  5144. return this._isIdentity;
  5145. };
  5146. /**
  5147. * Gets the determinant of the matrix
  5148. * @returns the matrix determinant
  5149. */
  5150. Matrix.prototype.determinant = function () {
  5151. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5152. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5153. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5154. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5155. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5156. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5157. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5158. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5159. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5160. };
  5161. // Methods
  5162. /**
  5163. * Returns the matrix as a Float32Array
  5164. * @returns the matrix underlying array
  5165. */
  5166. Matrix.prototype.toArray = function () {
  5167. return this.m;
  5168. };
  5169. /**
  5170. * Returns the matrix as a Float32Array
  5171. * @returns the matrix underlying array.
  5172. */
  5173. Matrix.prototype.asArray = function () {
  5174. return this.toArray();
  5175. };
  5176. /**
  5177. * Inverts the current matrix in place
  5178. * @returns the current inverted matrix
  5179. */
  5180. Matrix.prototype.invert = function () {
  5181. this.invertToRef(this);
  5182. return this;
  5183. };
  5184. /**
  5185. * Sets all the matrix elements to zero
  5186. * @returns the current matrix
  5187. */
  5188. Matrix.prototype.reset = function () {
  5189. for (var index = 0; index < 16; index++) {
  5190. this.m[index] = 0.0;
  5191. }
  5192. this._markAsUpdated();
  5193. return this;
  5194. };
  5195. /**
  5196. * Adds the current matrix with a second one
  5197. * @param other defines the matrix to add
  5198. * @returns a new matrix as the addition of the current matrix and the given one
  5199. */
  5200. Matrix.prototype.add = function (other) {
  5201. var result = new Matrix();
  5202. this.addToRef(other, result);
  5203. return result;
  5204. };
  5205. /**
  5206. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5207. * @param other defines the matrix to add
  5208. * @param result defines the target matrix
  5209. * @returns the current matrix
  5210. */
  5211. Matrix.prototype.addToRef = function (other, result) {
  5212. for (var index = 0; index < 16; index++) {
  5213. result.m[index] = this.m[index] + other.m[index];
  5214. }
  5215. result._markAsUpdated();
  5216. return this;
  5217. };
  5218. /**
  5219. * Adds in place the given matrix to the current matrix
  5220. * @param other defines the second operand
  5221. * @returns the current updated matrix
  5222. */
  5223. Matrix.prototype.addToSelf = function (other) {
  5224. for (var index = 0; index < 16; index++) {
  5225. this.m[index] += other.m[index];
  5226. }
  5227. this._markAsUpdated();
  5228. return this;
  5229. };
  5230. /**
  5231. * Sets the given matrix to the current inverted Matrix
  5232. * @param other defines the target matrix
  5233. * @returns the unmodified current matrix
  5234. */
  5235. Matrix.prototype.invertToRef = function (other) {
  5236. var l1 = this.m[0];
  5237. var l2 = this.m[1];
  5238. var l3 = this.m[2];
  5239. var l4 = this.m[3];
  5240. var l5 = this.m[4];
  5241. var l6 = this.m[5];
  5242. var l7 = this.m[6];
  5243. var l8 = this.m[7];
  5244. var l9 = this.m[8];
  5245. var l10 = this.m[9];
  5246. var l11 = this.m[10];
  5247. var l12 = this.m[11];
  5248. var l13 = this.m[12];
  5249. var l14 = this.m[13];
  5250. var l15 = this.m[14];
  5251. var l16 = this.m[15];
  5252. var l17 = (l11 * l16) - (l12 * l15);
  5253. var l18 = (l10 * l16) - (l12 * l14);
  5254. var l19 = (l10 * l15) - (l11 * l14);
  5255. var l20 = (l9 * l16) - (l12 * l13);
  5256. var l21 = (l9 * l15) - (l11 * l13);
  5257. var l22 = (l9 * l14) - (l10 * l13);
  5258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5263. var l28 = (l7 * l16) - (l8 * l15);
  5264. var l29 = (l6 * l16) - (l8 * l14);
  5265. var l30 = (l6 * l15) - (l7 * l14);
  5266. var l31 = (l5 * l16) - (l8 * l13);
  5267. var l32 = (l5 * l15) - (l7 * l13);
  5268. var l33 = (l5 * l14) - (l6 * l13);
  5269. var l34 = (l7 * l12) - (l8 * l11);
  5270. var l35 = (l6 * l12) - (l8 * l10);
  5271. var l36 = (l6 * l11) - (l7 * l10);
  5272. var l37 = (l5 * l12) - (l8 * l9);
  5273. var l38 = (l5 * l11) - (l7 * l9);
  5274. var l39 = (l5 * l10) - (l6 * l9);
  5275. other.m[0] = l23 * l27;
  5276. other.m[4] = l24 * l27;
  5277. other.m[8] = l25 * l27;
  5278. other.m[12] = l26 * l27;
  5279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5291. other._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Inserts the translation vector (using 3 floats) in the current matrix
  5296. * @param x defines the 1st component of the translation
  5297. * @param y defines the 2nd component of the translation
  5298. * @param z defines the 3rd component of the translation
  5299. * @returns the current updated matrix
  5300. */
  5301. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5302. this.m[12] = x;
  5303. this.m[13] = y;
  5304. this.m[14] = z;
  5305. this._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector in the current matrix
  5310. * @param vector3 defines the translation to insert
  5311. * @returns the current updated matrix
  5312. */
  5313. Matrix.prototype.setTranslation = function (vector3) {
  5314. this.m[12] = vector3.x;
  5315. this.m[13] = vector3.y;
  5316. this.m[14] = vector3.z;
  5317. this._markAsUpdated();
  5318. return this;
  5319. };
  5320. /**
  5321. * Gets the translation value of the current matrix
  5322. * @returns a new Vector3 as the extracted translation from the matrix
  5323. */
  5324. Matrix.prototype.getTranslation = function () {
  5325. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5326. };
  5327. /**
  5328. * Fill a Vector3 with the extracted translation from the matrix
  5329. * @param result defines the Vector3 where to store the translation
  5330. * @returns the current matrix
  5331. */
  5332. Matrix.prototype.getTranslationToRef = function (result) {
  5333. result.x = this.m[12];
  5334. result.y = this.m[13];
  5335. result.z = this.m[14];
  5336. return this;
  5337. };
  5338. /**
  5339. * Remove rotation and scaling part from the matrix
  5340. * @returns the updated matrix
  5341. */
  5342. Matrix.prototype.removeRotationAndScaling = function () {
  5343. this.setRowFromFloats(0, 1, 0, 0, 0);
  5344. this.setRowFromFloats(1, 0, 1, 0, 0);
  5345. this.setRowFromFloats(2, 0, 0, 1, 0);
  5346. return this;
  5347. };
  5348. /**
  5349. * Multiply two matrices
  5350. * @param other defines the second operand
  5351. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5352. */
  5353. Matrix.prototype.multiply = function (other) {
  5354. var result = new Matrix();
  5355. this.multiplyToRef(other, result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Copy the current matrix from the given one
  5360. * @param other defines the source matrix
  5361. * @returns the current updated matrix
  5362. */
  5363. Matrix.prototype.copyFrom = function (other) {
  5364. for (var index = 0; index < 16; index++) {
  5365. this.m[index] = other.m[index];
  5366. }
  5367. this._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Populates the given array from the starting index with the current matrix values
  5372. * @param array defines the target array
  5373. * @param offset defines the offset in the target array where to start storing values
  5374. * @returns the current matrix
  5375. */
  5376. Matrix.prototype.copyToArray = function (array, offset) {
  5377. if (offset === void 0) { offset = 0; }
  5378. for (var index = 0; index < 16; index++) {
  5379. array[offset + index] = this.m[index];
  5380. }
  5381. return this;
  5382. };
  5383. /**
  5384. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5385. * @param other defines the second operand
  5386. * @param result defines the matrix where to store the multiplication
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.multiplyToRef = function (other, result) {
  5390. this.multiplyToArray(other, result.m, 0);
  5391. result._markAsUpdated();
  5392. return this;
  5393. };
  5394. /**
  5395. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5396. * @param other defines the second operand
  5397. * @param result defines the array where to store the multiplication
  5398. * @param offset defines the offset in the target array where to start storing values
  5399. * @returns the current matrix
  5400. */
  5401. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5402. var tm0 = this.m[0];
  5403. var tm1 = this.m[1];
  5404. var tm2 = this.m[2];
  5405. var tm3 = this.m[3];
  5406. var tm4 = this.m[4];
  5407. var tm5 = this.m[5];
  5408. var tm6 = this.m[6];
  5409. var tm7 = this.m[7];
  5410. var tm8 = this.m[8];
  5411. var tm9 = this.m[9];
  5412. var tm10 = this.m[10];
  5413. var tm11 = this.m[11];
  5414. var tm12 = this.m[12];
  5415. var tm13 = this.m[13];
  5416. var tm14 = this.m[14];
  5417. var tm15 = this.m[15];
  5418. var om0 = other.m[0];
  5419. var om1 = other.m[1];
  5420. var om2 = other.m[2];
  5421. var om3 = other.m[3];
  5422. var om4 = other.m[4];
  5423. var om5 = other.m[5];
  5424. var om6 = other.m[6];
  5425. var om7 = other.m[7];
  5426. var om8 = other.m[8];
  5427. var om9 = other.m[9];
  5428. var om10 = other.m[10];
  5429. var om11 = other.m[11];
  5430. var om12 = other.m[12];
  5431. var om13 = other.m[13];
  5432. var om14 = other.m[14];
  5433. var om15 = other.m[15];
  5434. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5435. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5436. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5437. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5438. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5439. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5440. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5441. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5442. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5443. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5444. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5445. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5446. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5447. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5448. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5449. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5450. return this;
  5451. };
  5452. /**
  5453. * Check equality between this matrix and a second one
  5454. * @param value defines the second matrix to compare
  5455. * @returns true is the current matrix and the given one values are strictly equal
  5456. */
  5457. Matrix.prototype.equals = function (value) {
  5458. return value &&
  5459. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5460. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5461. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5462. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5463. };
  5464. /**
  5465. * Clone the current matrix
  5466. * @returns a new matrix from the current matrix
  5467. */
  5468. Matrix.prototype.clone = function () {
  5469. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5470. };
  5471. /**
  5472. * Returns the name of the current matrix class
  5473. * @returns the string "Matrix"
  5474. */
  5475. Matrix.prototype.getClassName = function () {
  5476. return "Matrix";
  5477. };
  5478. /**
  5479. * Gets the hash code of the current matrix
  5480. * @returns the hash code
  5481. */
  5482. Matrix.prototype.getHashCode = function () {
  5483. var hash = this.m[0] || 0;
  5484. for (var i = 1; i < 16; i++) {
  5485. hash = (hash * 397) ^ (this.m[i] || 0);
  5486. }
  5487. return hash;
  5488. };
  5489. /**
  5490. * Decomposes the current Matrix into a translation, rotation and scaling components
  5491. * @param scale defines the scale vector3 given as a reference to update
  5492. * @param rotation defines the rotation quaternion given as a reference to update
  5493. * @param translation defines the translation vector3 given as a reference to update
  5494. * @returns true if operation was successful
  5495. */
  5496. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5497. if (translation) {
  5498. translation.x = this.m[12];
  5499. translation.y = this.m[13];
  5500. translation.z = this.m[14];
  5501. }
  5502. scale = scale || MathTmp.Vector3[0];
  5503. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5504. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5505. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5506. if (this.determinant() <= 0) {
  5507. scale.y *= -1;
  5508. }
  5509. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5510. if (rotation) {
  5511. rotation.x = 0;
  5512. rotation.y = 0;
  5513. rotation.z = 0;
  5514. rotation.w = 1;
  5515. }
  5516. return false;
  5517. }
  5518. if (rotation) {
  5519. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5520. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5521. }
  5522. return true;
  5523. };
  5524. /**
  5525. * Gets specific row of the matrix
  5526. * @param index defines the number of the row to get
  5527. * @returns the index-th row of the current matrix as a new Vector4
  5528. */
  5529. Matrix.prototype.getRow = function (index) {
  5530. if (index < 0 || index > 3) {
  5531. return null;
  5532. }
  5533. var i = index * 4;
  5534. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5535. };
  5536. /**
  5537. * Sets the index-th row of the current matrix to the vector4 values
  5538. * @param index defines the number of the row to set
  5539. * @param row defines the target vector4
  5540. * @returns the updated current matrix
  5541. */
  5542. Matrix.prototype.setRow = function (index, row) {
  5543. if (index < 0 || index > 3) {
  5544. return this;
  5545. }
  5546. var i = index * 4;
  5547. this.m[i + 0] = row.x;
  5548. this.m[i + 1] = row.y;
  5549. this.m[i + 2] = row.z;
  5550. this.m[i + 3] = row.w;
  5551. this._markAsUpdated();
  5552. return this;
  5553. };
  5554. /**
  5555. * Compute the transpose of the matrix
  5556. * @returns the new transposed matrix
  5557. */
  5558. Matrix.prototype.transpose = function () {
  5559. return Matrix.Transpose(this);
  5560. };
  5561. /**
  5562. * Compute the transpose of the matrix and store it in a given matrix
  5563. * @param result defines the target matrix
  5564. * @returns the current matrix
  5565. */
  5566. Matrix.prototype.transposeToRef = function (result) {
  5567. Matrix.TransposeToRef(this, result);
  5568. return this;
  5569. };
  5570. /**
  5571. * Sets the index-th row of the current matrix with the given 4 x float values
  5572. * @param index defines the row index
  5573. * @param x defines the x component to set
  5574. * @param y defines the y component to set
  5575. * @param z defines the z component to set
  5576. * @param w defines the w component to set
  5577. * @returns the updated current matrix
  5578. */
  5579. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5580. if (index < 0 || index > 3) {
  5581. return this;
  5582. }
  5583. var i = index * 4;
  5584. this.m[i + 0] = x;
  5585. this.m[i + 1] = y;
  5586. this.m[i + 2] = z;
  5587. this.m[i + 3] = w;
  5588. this._markAsUpdated();
  5589. return this;
  5590. };
  5591. /**
  5592. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5593. * @param scale defines the scale factor
  5594. * @returns a new matrix
  5595. */
  5596. Matrix.prototype.scale = function (scale) {
  5597. var result = new Matrix();
  5598. this.scaleToRef(scale, result);
  5599. return result;
  5600. };
  5601. /**
  5602. * Scale the current matrix values by a factor to a given result matrix
  5603. * @param scale defines the scale factor
  5604. * @param result defines the matrix to store the result
  5605. * @returns the current matrix
  5606. */
  5607. Matrix.prototype.scaleToRef = function (scale, result) {
  5608. for (var index = 0; index < 16; index++) {
  5609. result.m[index] = this.m[index] * scale;
  5610. }
  5611. result._markAsUpdated();
  5612. return this;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor and add the result to a given matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the Matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] += this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5629. * @param ref matrix to store the result
  5630. */
  5631. Matrix.prototype.toNormalMatrix = function (ref) {
  5632. this.invertToRef(ref);
  5633. ref.transpose();
  5634. var m = ref.m;
  5635. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5636. };
  5637. /**
  5638. * Gets only rotation part of the current matrix
  5639. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5640. */
  5641. Matrix.prototype.getRotationMatrix = function () {
  5642. var result = Matrix.Identity();
  5643. this.getRotationMatrixToRef(result);
  5644. return result;
  5645. };
  5646. /**
  5647. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5648. * @param result defines the target matrix to store data to
  5649. * @returns the current matrix
  5650. */
  5651. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5652. var m = this.m;
  5653. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5654. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5655. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5656. if (this.determinant() <= 0) {
  5657. sy *= -1;
  5658. }
  5659. if (sx === 0 || sy === 0 || sz === 0) {
  5660. Matrix.IdentityToRef(result);
  5661. }
  5662. else {
  5663. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5664. }
  5665. return this;
  5666. };
  5667. // Statics
  5668. /**
  5669. * Creates a matrix from an array
  5670. * @param array defines the source array
  5671. * @param offset defines an offset in the source array
  5672. * @returns a new Matrix set from the starting index of the given array
  5673. */
  5674. Matrix.FromArray = function (array, offset) {
  5675. var result = new Matrix();
  5676. if (!offset) {
  5677. offset = 0;
  5678. }
  5679. Matrix.FromArrayToRef(array, offset, result);
  5680. return result;
  5681. };
  5682. /**
  5683. * Copy the content of an array into a given matrix
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @param result defines the target matrix
  5687. */
  5688. Matrix.FromArrayToRef = function (array, offset, result) {
  5689. for (var index = 0; index < 16; index++) {
  5690. result.m[index] = array[index + offset];
  5691. }
  5692. result._markAsUpdated();
  5693. };
  5694. /**
  5695. * Stores an array into a matrix after having multiplied each component by a given factor
  5696. * @param array defines the source array
  5697. * @param offset defines the offset in the source array
  5698. * @param scale defines the scaling factor
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset] * scale;
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores a list of values (16) inside a given matrix
  5709. * @param initialM11 defines 1st value of 1st row
  5710. * @param initialM12 defines 2nd value of 1st row
  5711. * @param initialM13 defines 3rd value of 1st row
  5712. * @param initialM14 defines 4th value of 1st row
  5713. * @param initialM21 defines 1st value of 2nd row
  5714. * @param initialM22 defines 2nd value of 2nd row
  5715. * @param initialM23 defines 3rd value of 2nd row
  5716. * @param initialM24 defines 4th value of 2nd row
  5717. * @param initialM31 defines 1st value of 3rd row
  5718. * @param initialM32 defines 2nd value of 3rd row
  5719. * @param initialM33 defines 3rd value of 3rd row
  5720. * @param initialM34 defines 4th value of 3rd row
  5721. * @param initialM41 defines 1st value of 4th row
  5722. * @param initialM42 defines 2nd value of 4th row
  5723. * @param initialM43 defines 3rd value of 4th row
  5724. * @param initialM44 defines 4th value of 4th row
  5725. * @param result defines the target matrix
  5726. */
  5727. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5728. result.m[0] = initialM11;
  5729. result.m[1] = initialM12;
  5730. result.m[2] = initialM13;
  5731. result.m[3] = initialM14;
  5732. result.m[4] = initialM21;
  5733. result.m[5] = initialM22;
  5734. result.m[6] = initialM23;
  5735. result.m[7] = initialM24;
  5736. result.m[8] = initialM31;
  5737. result.m[9] = initialM32;
  5738. result.m[10] = initialM33;
  5739. result.m[11] = initialM34;
  5740. result.m[12] = initialM41;
  5741. result.m[13] = initialM42;
  5742. result.m[14] = initialM43;
  5743. result.m[15] = initialM44;
  5744. result._markAsUpdated();
  5745. };
  5746. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5747. /**
  5748. * Gets an identity matrix that must not be updated
  5749. */
  5750. get: function () {
  5751. return Matrix._identityReadOnly;
  5752. },
  5753. enumerable: true,
  5754. configurable: true
  5755. });
  5756. /**
  5757. * Creates new matrix from a list of values (16)
  5758. * @param initialM11 defines 1st value of 1st row
  5759. * @param initialM12 defines 2nd value of 1st row
  5760. * @param initialM13 defines 3rd value of 1st row
  5761. * @param initialM14 defines 4th value of 1st row
  5762. * @param initialM21 defines 1st value of 2nd row
  5763. * @param initialM22 defines 2nd value of 2nd row
  5764. * @param initialM23 defines 3rd value of 2nd row
  5765. * @param initialM24 defines 4th value of 2nd row
  5766. * @param initialM31 defines 1st value of 3rd row
  5767. * @param initialM32 defines 2nd value of 3rd row
  5768. * @param initialM33 defines 3rd value of 3rd row
  5769. * @param initialM34 defines 4th value of 3rd row
  5770. * @param initialM41 defines 1st value of 4th row
  5771. * @param initialM42 defines 2nd value of 4th row
  5772. * @param initialM43 defines 3rd value of 4th row
  5773. * @param initialM44 defines 4th value of 4th row
  5774. * @returns the new matrix
  5775. */
  5776. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5777. var result = new Matrix();
  5778. result.m[0] = initialM11;
  5779. result.m[1] = initialM12;
  5780. result.m[2] = initialM13;
  5781. result.m[3] = initialM14;
  5782. result.m[4] = initialM21;
  5783. result.m[5] = initialM22;
  5784. result.m[6] = initialM23;
  5785. result.m[7] = initialM24;
  5786. result.m[8] = initialM31;
  5787. result.m[9] = initialM32;
  5788. result.m[10] = initialM33;
  5789. result.m[11] = initialM34;
  5790. result.m[12] = initialM41;
  5791. result.m[13] = initialM42;
  5792. result.m[14] = initialM43;
  5793. result.m[15] = initialM44;
  5794. return result;
  5795. };
  5796. /**
  5797. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5798. * @param scale defines the scale vector3
  5799. * @param rotation defines the rotation quaternion
  5800. * @param translation defines the translation vector3
  5801. * @returns a new matrix
  5802. */
  5803. Matrix.Compose = function (scale, rotation, translation) {
  5804. var result = Matrix.Identity();
  5805. Matrix.ComposeToRef(scale, rotation, translation, result);
  5806. return result;
  5807. };
  5808. /**
  5809. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5810. * @param scale defines the scale vector3
  5811. * @param rotation defines the rotation quaternion
  5812. * @param translation defines the translation vector3
  5813. * @param result defines the target matrix
  5814. */
  5815. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5816. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5817. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5818. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5819. result.setTranslation(translation);
  5820. };
  5821. /**
  5822. * Creates a new identity matrix
  5823. * @returns a new identity matrix
  5824. */
  5825. Matrix.Identity = function () {
  5826. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5827. };
  5828. /**
  5829. * Creates a new identity matrix and stores the result in a given matrix
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.IdentityToRef = function (result) {
  5833. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5834. };
  5835. /**
  5836. * Creates a new zero matrix
  5837. * @returns a new zero matrix
  5838. */
  5839. Matrix.Zero = function () {
  5840. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5841. };
  5842. /**
  5843. * Creates a new rotation matrix for "angle" radians around the X axis
  5844. * @param angle defines the angle (in radians) to use
  5845. * @return the new matrix
  5846. */
  5847. Matrix.RotationX = function (angle) {
  5848. var result = new Matrix();
  5849. Matrix.RotationXToRef(angle, result);
  5850. return result;
  5851. };
  5852. /**
  5853. * Creates a new matrix as the invert of a given matrix
  5854. * @param source defines the source matrix
  5855. * @returns the new matrix
  5856. */
  5857. Matrix.Invert = function (source) {
  5858. var result = new Matrix();
  5859. source.invertToRef(result);
  5860. return result;
  5861. };
  5862. /**
  5863. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5864. * @param angle defines the angle (in radians) to use
  5865. * @param result defines the target matrix
  5866. */
  5867. Matrix.RotationXToRef = function (angle, result) {
  5868. var s = Math.sin(angle);
  5869. var c = Math.cos(angle);
  5870. result.m[0] = 1.0;
  5871. result.m[15] = 1.0;
  5872. result.m[5] = c;
  5873. result.m[10] = c;
  5874. result.m[9] = -s;
  5875. result.m[6] = s;
  5876. result.m[1] = 0.0;
  5877. result.m[2] = 0.0;
  5878. result.m[3] = 0.0;
  5879. result.m[4] = 0.0;
  5880. result.m[7] = 0.0;
  5881. result.m[8] = 0.0;
  5882. result.m[11] = 0.0;
  5883. result.m[12] = 0.0;
  5884. result.m[13] = 0.0;
  5885. result.m[14] = 0.0;
  5886. result._markAsUpdated();
  5887. };
  5888. /**
  5889. * Creates a new rotation matrix for "angle" radians around the Y axis
  5890. * @param angle defines the angle (in radians) to use
  5891. * @return the new matrix
  5892. */
  5893. Matrix.RotationY = function (angle) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYToRef(angle, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5900. * @param angle defines the angle (in radians) to use
  5901. * @param result defines the target matrix
  5902. */
  5903. Matrix.RotationYToRef = function (angle, result) {
  5904. var s = Math.sin(angle);
  5905. var c = Math.cos(angle);
  5906. result.m[5] = 1.0;
  5907. result.m[15] = 1.0;
  5908. result.m[0] = c;
  5909. result.m[2] = -s;
  5910. result.m[8] = s;
  5911. result.m[10] = c;
  5912. result.m[1] = 0.0;
  5913. result.m[3] = 0.0;
  5914. result.m[4] = 0.0;
  5915. result.m[6] = 0.0;
  5916. result.m[7] = 0.0;
  5917. result.m[9] = 0.0;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result._markAsUpdated();
  5923. };
  5924. /**
  5925. * Creates a new rotation matrix for "angle" radians around the Z axis
  5926. * @param angle defines the angle (in radians) to use
  5927. * @return the new matrix
  5928. */
  5929. Matrix.RotationZ = function (angle) {
  5930. var result = new Matrix();
  5931. Matrix.RotationZToRef(angle, result);
  5932. return result;
  5933. };
  5934. /**
  5935. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5936. * @param angle defines the angle (in radians) to use
  5937. * @param result defines the target matrix
  5938. */
  5939. Matrix.RotationZToRef = function (angle, result) {
  5940. var s = Math.sin(angle);
  5941. var c = Math.cos(angle);
  5942. result.m[10] = 1.0;
  5943. result.m[15] = 1.0;
  5944. result.m[0] = c;
  5945. result.m[1] = s;
  5946. result.m[4] = -s;
  5947. result.m[5] = c;
  5948. result.m[2] = 0.0;
  5949. result.m[3] = 0.0;
  5950. result.m[6] = 0.0;
  5951. result.m[7] = 0.0;
  5952. result.m[8] = 0.0;
  5953. result.m[9] = 0.0;
  5954. result.m[11] = 0.0;
  5955. result.m[12] = 0.0;
  5956. result.m[13] = 0.0;
  5957. result.m[14] = 0.0;
  5958. result._markAsUpdated();
  5959. };
  5960. /**
  5961. * Creates a new rotation matrix for "angle" radians around the given axis
  5962. * @param axis defines the axis to use
  5963. * @param angle defines the angle (in radians) to use
  5964. * @return the new matrix
  5965. */
  5966. Matrix.RotationAxis = function (axis, angle) {
  5967. var result = Matrix.Zero();
  5968. Matrix.RotationAxisToRef(axis, angle, result);
  5969. return result;
  5970. };
  5971. /**
  5972. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5973. * @param axis defines the axis to use
  5974. * @param angle defines the angle (in radians) to use
  5975. * @param result defines the target matrix
  5976. */
  5977. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5978. var s = Math.sin(-angle);
  5979. var c = Math.cos(-angle);
  5980. var c1 = 1 - c;
  5981. axis.normalize();
  5982. result.m[0] = (axis.x * axis.x) * c1 + c;
  5983. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5984. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5985. result.m[3] = 0.0;
  5986. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5987. result.m[5] = (axis.y * axis.y) * c1 + c;
  5988. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5989. result.m[7] = 0.0;
  5990. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5991. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5992. result.m[10] = (axis.z * axis.z) * c1 + c;
  5993. result.m[11] = 0.0;
  5994. result.m[15] = 1.0;
  5995. result._markAsUpdated();
  5996. };
  5997. /**
  5998. * Creates a rotation matrix
  5999. * @param yaw defines the yaw angle in radians (Y axis)
  6000. * @param pitch defines the pitch angle in radians (X axis)
  6001. * @param roll defines the roll angle in radians (X axis)
  6002. * @returns the new rotation matrix
  6003. */
  6004. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6005. var result = new Matrix();
  6006. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Creates a rotation matrix and stores it in a given matrix
  6011. * @param yaw defines the yaw angle in radians (Y axis)
  6012. * @param pitch defines the pitch angle in radians (X axis)
  6013. * @param roll defines the roll angle in radians (X axis)
  6014. * @param result defines the target matrix
  6015. */
  6016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6018. this._tempQuaternion.toRotationMatrix(result);
  6019. };
  6020. /**
  6021. * Creates a scaling matrix
  6022. * @param x defines the scale factor on X axis
  6023. * @param y defines the scale factor on Y axis
  6024. * @param z defines the scale factor on Z axis
  6025. * @returns the new matrix
  6026. */
  6027. Matrix.Scaling = function (x, y, z) {
  6028. var result = Matrix.Zero();
  6029. Matrix.ScalingToRef(x, y, z, result);
  6030. return result;
  6031. };
  6032. /**
  6033. * Creates a scaling matrix and stores it in a given matrix
  6034. * @param x defines the scale factor on X axis
  6035. * @param y defines the scale factor on Y axis
  6036. * @param z defines the scale factor on Z axis
  6037. * @param result defines the target matrix
  6038. */
  6039. Matrix.ScalingToRef = function (x, y, z, result) {
  6040. result.m[0] = x;
  6041. result.m[1] = 0.0;
  6042. result.m[2] = 0.0;
  6043. result.m[3] = 0.0;
  6044. result.m[4] = 0.0;
  6045. result.m[5] = y;
  6046. result.m[6] = 0.0;
  6047. result.m[7] = 0.0;
  6048. result.m[8] = 0.0;
  6049. result.m[9] = 0.0;
  6050. result.m[10] = z;
  6051. result.m[11] = 0.0;
  6052. result.m[12] = 0.0;
  6053. result.m[13] = 0.0;
  6054. result.m[14] = 0.0;
  6055. result.m[15] = 1.0;
  6056. result._markAsUpdated();
  6057. };
  6058. /**
  6059. * Creates a translation matrix
  6060. * @param x defines the translation on X axis
  6061. * @param y defines the translation on Y axis
  6062. * @param z defines the translationon Z axis
  6063. * @returns the new matrix
  6064. */
  6065. Matrix.Translation = function (x, y, z) {
  6066. var result = Matrix.Identity();
  6067. Matrix.TranslationToRef(x, y, z, result);
  6068. return result;
  6069. };
  6070. /**
  6071. * Creates a translation matrix and stores it in a given matrix
  6072. * @param x defines the translation on X axis
  6073. * @param y defines the translation on Y axis
  6074. * @param z defines the translationon Z axis
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.TranslationToRef = function (x, y, z, result) {
  6078. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6079. };
  6080. /**
  6081. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6082. * @param startValue defines the start value
  6083. * @param endValue defines the end value
  6084. * @param gradient defines the gradient factor
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.Lerp = function (startValue, endValue, gradient) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6094. * @param startValue defines the start value
  6095. * @param endValue defines the end value
  6096. * @param gradient defines the gradient factor
  6097. * @param result defines the Matrix object where to store data
  6098. */
  6099. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6100. for (var index = 0; index < 16; index++) {
  6101. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6102. }
  6103. result._markAsUpdated();
  6104. };
  6105. /**
  6106. * Builds a new matrix whose values are computed by:
  6107. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6108. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6109. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6110. * @param startValue defines the first matrix
  6111. * @param endValue defines the second matrix
  6112. * @param gradient defines the gradient between the two matrices
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6116. var result = Matrix.Zero();
  6117. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Update a matrix to values which are computed by:
  6122. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6123. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6124. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6125. * @param startValue defines the first matrix
  6126. * @param endValue defines the second matrix
  6127. * @param gradient defines the gradient between the two matrices
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6131. var startScale = MathTmp.Vector3[0];
  6132. var startRotation = MathTmp.Quaternion[0];
  6133. var startTranslation = MathTmp.Vector3[1];
  6134. startValue.decompose(startScale, startRotation, startTranslation);
  6135. var endScale = MathTmp.Vector3[2];
  6136. var endRotation = MathTmp.Quaternion[1];
  6137. var endTranslation = MathTmp.Vector3[3];
  6138. endValue.decompose(endScale, endRotation, endTranslation);
  6139. var resultScale = MathTmp.Vector3[4];
  6140. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6141. var resultRotation = MathTmp.Quaternion[2];
  6142. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6143. var resultTranslation = MathTmp.Vector3[5];
  6144. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6145. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6146. };
  6147. /**
  6148. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6149. * This function works in left handed mode
  6150. * @param eye defines the final position of the entity
  6151. * @param target defines where the entity should look at
  6152. * @param up defines the up vector for the entity
  6153. * @returns the new matrix
  6154. */
  6155. Matrix.LookAtLH = function (eye, target, up) {
  6156. var result = Matrix.Zero();
  6157. Matrix.LookAtLHToRef(eye, target, up, result);
  6158. return result;
  6159. };
  6160. /**
  6161. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6169. // Z axis
  6170. target.subtractToRef(eye, this._zAxis);
  6171. this._zAxis.normalize();
  6172. // X axis
  6173. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6174. if (this._xAxis.lengthSquared() === 0) {
  6175. this._xAxis.x = 1.0;
  6176. }
  6177. else {
  6178. this._xAxis.normalize();
  6179. }
  6180. // Y axis
  6181. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6182. this._yAxis.normalize();
  6183. // Eye angles
  6184. var ex = -Vector3.Dot(this._xAxis, eye);
  6185. var ey = -Vector3.Dot(this._yAxis, eye);
  6186. var ez = -Vector3.Dot(this._zAxis, eye);
  6187. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6188. };
  6189. /**
  6190. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6191. * This function works in right handed mode
  6192. * @param eye defines the final position of the entity
  6193. * @param target defines where the entity should look at
  6194. * @param up defines the up vector for the entity
  6195. * @returns the new matrix
  6196. */
  6197. Matrix.LookAtRH = function (eye, target, up) {
  6198. var result = Matrix.Zero();
  6199. Matrix.LookAtRHToRef(eye, target, up, result);
  6200. return result;
  6201. };
  6202. /**
  6203. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @param result defines the target matrix
  6209. */
  6210. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6211. // Z axis
  6212. eye.subtractToRef(target, this._zAxis);
  6213. this._zAxis.normalize();
  6214. // X axis
  6215. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6216. if (this._xAxis.lengthSquared() === 0) {
  6217. this._xAxis.x = 1.0;
  6218. }
  6219. else {
  6220. this._xAxis.normalize();
  6221. }
  6222. // Y axis
  6223. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6224. this._yAxis.normalize();
  6225. // Eye angles
  6226. var ex = -Vector3.Dot(this._xAxis, eye);
  6227. var ey = -Vector3.Dot(this._yAxis, eye);
  6228. var ez = -Vector3.Dot(this._zAxis, eye);
  6229. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6230. };
  6231. /**
  6232. * Create a left-handed orthographic projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Store a left-handed orthographic projection to a given matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @param result defines the target matrix
  6251. */
  6252. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6253. var n = znear;
  6254. var f = zfar;
  6255. var a = 2.0 / width;
  6256. var b = 2.0 / height;
  6257. var c = 2.0 / (f - n);
  6258. var d = -(f + n) / (f - n);
  6259. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6260. };
  6261. /**
  6262. * Create a left-handed orthographic projection matrix
  6263. * @param left defines the viewport left coordinate
  6264. * @param right defines the viewport right coordinate
  6265. * @param bottom defines the viewport bottom coordinate
  6266. * @param top defines the viewport top coordinate
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @returns a new matrix as a left-handed orthographic projection matrix
  6270. */
  6271. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6272. var matrix = Matrix.Zero();
  6273. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6274. return matrix;
  6275. };
  6276. /**
  6277. * Stores a left-handed orthographic projection into a given matrix
  6278. * @param left defines the viewport left coordinate
  6279. * @param right defines the viewport right coordinate
  6280. * @param bottom defines the viewport bottom coordinate
  6281. * @param top defines the viewport top coordinate
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. */
  6286. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6287. var n = znear;
  6288. var f = zfar;
  6289. var a = 2.0 / (right - left);
  6290. var b = 2.0 / (top - bottom);
  6291. var c = 2.0 / (f - n);
  6292. var d = -(f + n) / (f - n);
  6293. var i0 = (left + right) / (left - right);
  6294. var i1 = (top + bottom) / (bottom - top);
  6295. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6296. };
  6297. /**
  6298. * Creates a right-handed orthographic projection matrix
  6299. * @param left defines the viewport left coordinate
  6300. * @param right defines the viewport right coordinate
  6301. * @param bottom defines the viewport bottom coordinate
  6302. * @param top defines the viewport top coordinate
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a right-handed orthographic projection matrix
  6306. */
  6307. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6310. return matrix;
  6311. };
  6312. /**
  6313. * Stores a right-handed orthographic projection into a given matrix
  6314. * @param left defines the viewport left coordinate
  6315. * @param right defines the viewport right coordinate
  6316. * @param bottom defines the viewport bottom coordinate
  6317. * @param top defines the viewport top coordinate
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @param result defines the target matrix
  6321. */
  6322. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6323. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6324. result.m[10] *= -1.0;
  6325. };
  6326. /**
  6327. * Creates a left-handed perspective projection matrix
  6328. * @param width defines the viewport width
  6329. * @param height defines the viewport height
  6330. * @param znear defines the near clip plane
  6331. * @param zfar defines the far clip plane
  6332. * @returns a new matrix as a left-handed perspective projection matrix
  6333. */
  6334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6335. var matrix = Matrix.Zero();
  6336. var n = znear;
  6337. var f = zfar;
  6338. var a = 2.0 * n / width;
  6339. var b = 2.0 * n / height;
  6340. var c = (f + n) / (f - n);
  6341. var d = -2.0 * f * n / (f - n);
  6342. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6343. return matrix;
  6344. };
  6345. /**
  6346. * Creates a left-handed perspective projection matrix
  6347. * @param fov defines the horizontal field of view
  6348. * @param aspect defines the aspect ratio
  6349. * @param znear defines the near clip plane
  6350. * @param zfar defines the far clip plane
  6351. * @returns a new matrix as a left-handed perspective projection matrix
  6352. */
  6353. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6354. var matrix = Matrix.Zero();
  6355. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Stores a left-handed perspective projection into a given matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @param result defines the target matrix
  6365. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6366. */
  6367. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6368. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6369. var n = znear;
  6370. var f = zfar;
  6371. var t = 1.0 / (Math.tan(fov * 0.5));
  6372. var a = isVerticalFovFixed ? (t / aspect) : t;
  6373. var b = isVerticalFovFixed ? t : (t * aspect);
  6374. var c = (f + n) / (f - n);
  6375. var d = -2.0 * f * n / (f - n);
  6376. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6377. };
  6378. /**
  6379. * Creates a right-handed perspective projection matrix
  6380. * @param fov defines the horizontal field of view
  6381. * @param aspect defines the aspect ratio
  6382. * @param znear defines the near clip plane
  6383. * @param zfar defines the far clip plane
  6384. * @returns a new matrix as a right-handed perspective projection matrix
  6385. */
  6386. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6387. var matrix = Matrix.Zero();
  6388. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6389. return matrix;
  6390. };
  6391. /**
  6392. * Stores a right-handed perspective projection into a given matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @param result defines the target matrix
  6398. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6399. */
  6400. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6401. //alternatively this could be expressed as:
  6402. // m = PerspectiveFovLHToRef
  6403. // m[10] *= -1.0;
  6404. // m[11] *= -1.0;
  6405. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6406. var n = znear;
  6407. var f = zfar;
  6408. var t = 1.0 / (Math.tan(fov * 0.5));
  6409. var a = isVerticalFovFixed ? (t / aspect) : t;
  6410. var b = isVerticalFovFixed ? t : (t * aspect);
  6411. var c = -(f + n) / (f - n);
  6412. var d = -2 * f * n / (f - n);
  6413. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6414. };
  6415. /**
  6416. * Stores a perspective projection for WebVR info a given matrix
  6417. * @param fov defines the field of view
  6418. * @param znear defines the near clip plane
  6419. * @param zfar defines the far clip plane
  6420. * @param result defines the target matrix
  6421. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6422. */
  6423. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6424. if (rightHanded === void 0) { rightHanded = false; }
  6425. var rightHandedFactor = rightHanded ? -1 : 1;
  6426. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6427. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6428. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6429. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6430. var xScale = 2.0 / (leftTan + rightTan);
  6431. var yScale = 2.0 / (upTan + downTan);
  6432. result.m[0] = xScale;
  6433. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6434. result.m[5] = yScale;
  6435. result.m[6] = result.m[7] = 0.0;
  6436. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6437. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6438. result.m[10] = -zfar / (znear - zfar);
  6439. result.m[11] = 1.0 * rightHandedFactor;
  6440. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6441. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6442. result._markAsUpdated();
  6443. };
  6444. /**
  6445. * Computes a complete transformation matrix
  6446. * @param viewport defines the viewport to use
  6447. * @param world defines the world matrix
  6448. * @param view defines the view matrix
  6449. * @param projection defines the projection matrix
  6450. * @param zmin defines the near clip plane
  6451. * @param zmax defines the far clip plane
  6452. * @returns the transformation matrix
  6453. */
  6454. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6455. var cw = viewport.width;
  6456. var ch = viewport.height;
  6457. var cx = viewport.x;
  6458. var cy = viewport.y;
  6459. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6460. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6461. };
  6462. /**
  6463. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6464. * @param matrix defines the matrix to use
  6465. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6466. */
  6467. Matrix.GetAsMatrix2x2 = function (matrix) {
  6468. return new Float32Array([
  6469. matrix.m[0], matrix.m[1],
  6470. matrix.m[4], matrix.m[5]
  6471. ]);
  6472. };
  6473. /**
  6474. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6475. * @param matrix defines the matrix to use
  6476. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6477. */
  6478. Matrix.GetAsMatrix3x3 = function (matrix) {
  6479. return new Float32Array([
  6480. matrix.m[0], matrix.m[1], matrix.m[2],
  6481. matrix.m[4], matrix.m[5], matrix.m[6],
  6482. matrix.m[8], matrix.m[9], matrix.m[10]
  6483. ]);
  6484. };
  6485. /**
  6486. * Compute the transpose of a given matrix
  6487. * @param matrix defines the matrix to transpose
  6488. * @returns the new matrix
  6489. */
  6490. Matrix.Transpose = function (matrix) {
  6491. var result = new Matrix();
  6492. Matrix.TransposeToRef(matrix, result);
  6493. return result;
  6494. };
  6495. /**
  6496. * Compute the transpose of a matrix and store it in a target matrix
  6497. * @param matrix defines the matrix to transpose
  6498. * @param result defines the target matrix
  6499. */
  6500. Matrix.TransposeToRef = function (matrix, result) {
  6501. result.m[0] = matrix.m[0];
  6502. result.m[1] = matrix.m[4];
  6503. result.m[2] = matrix.m[8];
  6504. result.m[3] = matrix.m[12];
  6505. result.m[4] = matrix.m[1];
  6506. result.m[5] = matrix.m[5];
  6507. result.m[6] = matrix.m[9];
  6508. result.m[7] = matrix.m[13];
  6509. result.m[8] = matrix.m[2];
  6510. result.m[9] = matrix.m[6];
  6511. result.m[10] = matrix.m[10];
  6512. result.m[11] = matrix.m[14];
  6513. result.m[12] = matrix.m[3];
  6514. result.m[13] = matrix.m[7];
  6515. result.m[14] = matrix.m[11];
  6516. result.m[15] = matrix.m[15];
  6517. };
  6518. /**
  6519. * Computes a reflection matrix from a plane
  6520. * @param plane defines the reflection plane
  6521. * @returns a new matrix
  6522. */
  6523. Matrix.Reflection = function (plane) {
  6524. var matrix = new Matrix();
  6525. Matrix.ReflectionToRef(plane, matrix);
  6526. return matrix;
  6527. };
  6528. /**
  6529. * Computes a reflection matrix from a plane
  6530. * @param plane defines the reflection plane
  6531. * @param result defines the target matrix
  6532. */
  6533. Matrix.ReflectionToRef = function (plane, result) {
  6534. plane.normalize();
  6535. var x = plane.normal.x;
  6536. var y = plane.normal.y;
  6537. var z = plane.normal.z;
  6538. var temp = -2 * x;
  6539. var temp2 = -2 * y;
  6540. var temp3 = -2 * z;
  6541. result.m[0] = (temp * x) + 1;
  6542. result.m[1] = temp2 * x;
  6543. result.m[2] = temp3 * x;
  6544. result.m[3] = 0.0;
  6545. result.m[4] = temp * y;
  6546. result.m[5] = (temp2 * y) + 1;
  6547. result.m[6] = temp3 * y;
  6548. result.m[7] = 0.0;
  6549. result.m[8] = temp * z;
  6550. result.m[9] = temp2 * z;
  6551. result.m[10] = (temp3 * z) + 1;
  6552. result.m[11] = 0.0;
  6553. result.m[12] = temp * plane.d;
  6554. result.m[13] = temp2 * plane.d;
  6555. result.m[14] = temp3 * plane.d;
  6556. result.m[15] = 1.0;
  6557. result._markAsUpdated();
  6558. };
  6559. /**
  6560. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6561. * @param xaxis defines the value of the 1st axis
  6562. * @param yaxis defines the value of the 2nd axis
  6563. * @param zaxis defines the value of the 3rd axis
  6564. * @param result defines the target matrix
  6565. */
  6566. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6567. result.m[0] = xaxis.x;
  6568. result.m[1] = xaxis.y;
  6569. result.m[2] = xaxis.z;
  6570. result.m[3] = 0.0;
  6571. result.m[4] = yaxis.x;
  6572. result.m[5] = yaxis.y;
  6573. result.m[6] = yaxis.z;
  6574. result.m[7] = 0.0;
  6575. result.m[8] = zaxis.x;
  6576. result.m[9] = zaxis.y;
  6577. result.m[10] = zaxis.z;
  6578. result.m[11] = 0.0;
  6579. result.m[12] = 0.0;
  6580. result.m[13] = 0.0;
  6581. result.m[14] = 0.0;
  6582. result.m[15] = 1.0;
  6583. result._markAsUpdated();
  6584. };
  6585. /**
  6586. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6587. * @param quat defines the quaternion to use
  6588. * @param result defines the target matrix
  6589. */
  6590. Matrix.FromQuaternionToRef = function (quat, result) {
  6591. var xx = quat.x * quat.x;
  6592. var yy = quat.y * quat.y;
  6593. var zz = quat.z * quat.z;
  6594. var xy = quat.x * quat.y;
  6595. var zw = quat.z * quat.w;
  6596. var zx = quat.z * quat.x;
  6597. var yw = quat.y * quat.w;
  6598. var yz = quat.y * quat.z;
  6599. var xw = quat.x * quat.w;
  6600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6601. result.m[1] = 2.0 * (xy + zw);
  6602. result.m[2] = 2.0 * (zx - yw);
  6603. result.m[3] = 0.0;
  6604. result.m[4] = 2.0 * (xy - zw);
  6605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6606. result.m[6] = 2.0 * (yz + xw);
  6607. result.m[7] = 0.0;
  6608. result.m[8] = 2.0 * (zx + yw);
  6609. result.m[9] = 2.0 * (yz - xw);
  6610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6611. result.m[11] = 0.0;
  6612. result.m[12] = 0.0;
  6613. result.m[13] = 0.0;
  6614. result.m[14] = 0.0;
  6615. result.m[15] = 1.0;
  6616. result._markAsUpdated();
  6617. };
  6618. Matrix._tempQuaternion = new Quaternion();
  6619. Matrix._xAxis = Vector3.Zero();
  6620. Matrix._yAxis = Vector3.Zero();
  6621. Matrix._zAxis = Vector3.Zero();
  6622. Matrix._updateFlagSeed = 0;
  6623. Matrix._identityReadOnly = Matrix.Identity();
  6624. return Matrix;
  6625. }());
  6626. BABYLON.Matrix = Matrix;
  6627. var Plane = /** @class */ (function () {
  6628. /**
  6629. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6630. */
  6631. function Plane(a, b, c, d) {
  6632. this.normal = new Vector3(a, b, c);
  6633. this.d = d;
  6634. }
  6635. /**
  6636. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6637. */
  6638. Plane.prototype.asArray = function () {
  6639. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6640. };
  6641. // Methods
  6642. /**
  6643. * Returns a new plane copied from the current Plane.
  6644. */
  6645. Plane.prototype.clone = function () {
  6646. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6647. };
  6648. /**
  6649. * Returns the string "Plane".
  6650. */
  6651. Plane.prototype.getClassName = function () {
  6652. return "Plane";
  6653. };
  6654. /**
  6655. * Returns the Plane hash code.
  6656. */
  6657. Plane.prototype.getHashCode = function () {
  6658. var hash = this.normal.getHashCode();
  6659. hash = (hash * 397) ^ (this.d || 0);
  6660. return hash;
  6661. };
  6662. /**
  6663. * Normalize the current Plane in place.
  6664. * Returns the updated Plane.
  6665. */
  6666. Plane.prototype.normalize = function () {
  6667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6668. var magnitude = 0.0;
  6669. if (norm !== 0) {
  6670. magnitude = 1.0 / norm;
  6671. }
  6672. this.normal.x *= magnitude;
  6673. this.normal.y *= magnitude;
  6674. this.normal.z *= magnitude;
  6675. this.d *= magnitude;
  6676. return this;
  6677. };
  6678. /**
  6679. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6680. */
  6681. Plane.prototype.transform = function (transformation) {
  6682. var transposedMatrix = Matrix.Transpose(transformation);
  6683. var x = this.normal.x;
  6684. var y = this.normal.y;
  6685. var z = this.normal.z;
  6686. var d = this.d;
  6687. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6688. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6689. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6690. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6691. return new Plane(normalX, normalY, normalZ, finalD);
  6692. };
  6693. /**
  6694. * Returns the dot product (float) of the point coordinates and the plane normal.
  6695. */
  6696. Plane.prototype.dotCoordinate = function (point) {
  6697. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6698. };
  6699. /**
  6700. * Updates the current Plane from the plane defined by the three given points.
  6701. * Returns the updated Plane.
  6702. */
  6703. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6704. var x1 = point2.x - point1.x;
  6705. var y1 = point2.y - point1.y;
  6706. var z1 = point2.z - point1.z;
  6707. var x2 = point3.x - point1.x;
  6708. var y2 = point3.y - point1.y;
  6709. var z2 = point3.z - point1.z;
  6710. var yz = (y1 * z2) - (z1 * y2);
  6711. var xz = (z1 * x2) - (x1 * z2);
  6712. var xy = (x1 * y2) - (y1 * x2);
  6713. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6714. var invPyth;
  6715. if (pyth !== 0) {
  6716. invPyth = 1.0 / pyth;
  6717. }
  6718. else {
  6719. invPyth = 0.0;
  6720. }
  6721. this.normal.x = yz * invPyth;
  6722. this.normal.y = xz * invPyth;
  6723. this.normal.z = xy * invPyth;
  6724. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6725. return this;
  6726. };
  6727. /**
  6728. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6729. */
  6730. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6731. var dot = Vector3.Dot(this.normal, direction);
  6732. return (dot <= epsilon);
  6733. };
  6734. /**
  6735. * Returns the signed distance (float) from the given point to the Plane.
  6736. */
  6737. Plane.prototype.signedDistanceTo = function (point) {
  6738. return Vector3.Dot(point, this.normal) + this.d;
  6739. };
  6740. // Statics
  6741. /**
  6742. * Returns a new Plane from the given array.
  6743. */
  6744. Plane.FromArray = function (array) {
  6745. return new Plane(array[0], array[1], array[2], array[3]);
  6746. };
  6747. /**
  6748. * Returns a new Plane defined by the three given points.
  6749. */
  6750. Plane.FromPoints = function (point1, point2, point3) {
  6751. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6752. result.copyFromPoints(point1, point2, point3);
  6753. return result;
  6754. };
  6755. /**
  6756. * Returns a new Plane the normal vector to this plane at the given origin point.
  6757. * Note : the vector "normal" is updated because normalized.
  6758. */
  6759. Plane.FromPositionAndNormal = function (origin, normal) {
  6760. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6761. normal.normalize();
  6762. result.normal = normal;
  6763. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6764. return result;
  6765. };
  6766. /**
  6767. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6768. */
  6769. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6770. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6771. return Vector3.Dot(point, normal) + d;
  6772. };
  6773. return Plane;
  6774. }());
  6775. BABYLON.Plane = Plane;
  6776. var Viewport = /** @class */ (function () {
  6777. /**
  6778. * Creates a Viewport object located at (x, y) and sized (width, height).
  6779. */
  6780. function Viewport(x, y, width, height) {
  6781. this.x = x;
  6782. this.y = y;
  6783. this.width = width;
  6784. this.height = height;
  6785. }
  6786. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6787. if (renderWidthOrEngine.getRenderWidth) {
  6788. var engine = renderWidthOrEngine;
  6789. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6790. }
  6791. var renderWidth = renderWidthOrEngine;
  6792. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6793. };
  6794. /**
  6795. * Returns a new Viewport copied from the current one.
  6796. */
  6797. Viewport.prototype.clone = function () {
  6798. return new Viewport(this.x, this.y, this.width, this.height);
  6799. };
  6800. return Viewport;
  6801. }());
  6802. BABYLON.Viewport = Viewport;
  6803. var Frustum = /** @class */ (function () {
  6804. function Frustum() {
  6805. }
  6806. /**
  6807. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6808. */
  6809. Frustum.GetPlanes = function (transform) {
  6810. var frustumPlanes = [];
  6811. for (var index = 0; index < 6; index++) {
  6812. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6813. }
  6814. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6815. return frustumPlanes;
  6816. };
  6817. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6818. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6819. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6820. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6821. frustumPlane.d = transform.m[15] + transform.m[14];
  6822. frustumPlane.normalize();
  6823. };
  6824. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6825. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6826. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6827. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6828. frustumPlane.d = transform.m[15] - transform.m[14];
  6829. frustumPlane.normalize();
  6830. };
  6831. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6835. frustumPlane.d = transform.m[15] + transform.m[12];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6842. frustumPlane.d = transform.m[15] - transform.m[12];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6847. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6848. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6849. frustumPlane.d = transform.m[15] - transform.m[13];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6856. frustumPlane.d = transform.m[15] + transform.m[13];
  6857. frustumPlane.normalize();
  6858. };
  6859. /**
  6860. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6861. */
  6862. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6863. // Near
  6864. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6865. // Far
  6866. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6867. // Left
  6868. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6869. // Right
  6870. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6871. // Top
  6872. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6873. // Bottom
  6874. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6875. };
  6876. return Frustum;
  6877. }());
  6878. BABYLON.Frustum = Frustum;
  6879. /** Defines supported spaces */
  6880. var Space;
  6881. (function (Space) {
  6882. /** Local (object) space */
  6883. Space[Space["LOCAL"] = 0] = "LOCAL";
  6884. /** World space */
  6885. Space[Space["WORLD"] = 1] = "WORLD";
  6886. /** Bone space */
  6887. Space[Space["BONE"] = 2] = "BONE";
  6888. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6889. /** Defines the 3 main axes */
  6890. var Axis = /** @class */ (function () {
  6891. function Axis() {
  6892. }
  6893. /** X axis */
  6894. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6895. /** Y axis */
  6896. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6897. /** Z axis */
  6898. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6899. return Axis;
  6900. }());
  6901. BABYLON.Axis = Axis;
  6902. ;
  6903. var BezierCurve = /** @class */ (function () {
  6904. function BezierCurve() {
  6905. }
  6906. /**
  6907. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6908. */
  6909. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6910. // Extract X (which is equal to time here)
  6911. var f0 = 1 - 3 * x2 + 3 * x1;
  6912. var f1 = 3 * x2 - 6 * x1;
  6913. var f2 = 3 * x1;
  6914. var refinedT = t;
  6915. for (var i = 0; i < 5; i++) {
  6916. var refinedT2 = refinedT * refinedT;
  6917. var refinedT3 = refinedT2 * refinedT;
  6918. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6919. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6920. refinedT -= (x - t) * slope;
  6921. refinedT = Math.min(1, Math.max(0, refinedT));
  6922. }
  6923. // Resolve cubic bezier for the given x
  6924. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6925. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6926. Math.pow(refinedT, 3);
  6927. };
  6928. return BezierCurve;
  6929. }());
  6930. BABYLON.BezierCurve = BezierCurve;
  6931. /**
  6932. * Defines potential orientation for back face culling
  6933. */
  6934. var Orientation;
  6935. (function (Orientation) {
  6936. /**
  6937. * Clockwise
  6938. */
  6939. Orientation[Orientation["CW"] = 0] = "CW";
  6940. /** Counter clockwise */
  6941. Orientation[Orientation["CCW"] = 1] = "CCW";
  6942. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6943. /**
  6944. * Defines angle representation
  6945. */
  6946. var Angle = /** @class */ (function () {
  6947. /**
  6948. * Creates an Angle object of "radians" radians (float).
  6949. */
  6950. function Angle(radians) {
  6951. this._radians = radians;
  6952. if (this._radians < 0.0)
  6953. this._radians += (2.0 * Math.PI);
  6954. }
  6955. /**
  6956. * Get value in degrees
  6957. * @returns the Angle value in degrees (float)
  6958. */
  6959. Angle.prototype.degrees = function () {
  6960. return this._radians * 180.0 / Math.PI;
  6961. };
  6962. /**
  6963. * Get value in radians
  6964. * @returns the Angle value in radians (float)
  6965. */
  6966. Angle.prototype.radians = function () {
  6967. return this._radians;
  6968. };
  6969. /**
  6970. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6971. * @param a defines first vector
  6972. * @param b defines second vector
  6973. * @returns a new Angle
  6974. */
  6975. Angle.BetweenTwoPoints = function (a, b) {
  6976. var delta = b.subtract(a);
  6977. var theta = Math.atan2(delta.y, delta.x);
  6978. return new Angle(theta);
  6979. };
  6980. /**
  6981. * Gets a new Angle object from the given float in radians
  6982. * @param radians defines the angle value in radians
  6983. * @returns a new Angle
  6984. */
  6985. Angle.FromRadians = function (radians) {
  6986. return new Angle(radians);
  6987. };
  6988. /**
  6989. * Gets a new Angle object from the given float in degrees
  6990. * @param degrees defines the angle value in degrees
  6991. * @returns a new Angle
  6992. */
  6993. Angle.FromDegrees = function (degrees) {
  6994. return new Angle(degrees * Math.PI / 180.0);
  6995. };
  6996. return Angle;
  6997. }());
  6998. BABYLON.Angle = Angle;
  6999. var Arc2 = /** @class */ (function () {
  7000. /**
  7001. * Creates an Arc object from the three given points : start, middle and end.
  7002. */
  7003. function Arc2(startPoint, midPoint, endPoint) {
  7004. this.startPoint = startPoint;
  7005. this.midPoint = midPoint;
  7006. this.endPoint = endPoint;
  7007. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7008. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7009. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7010. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7011. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7012. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7013. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7014. var a1 = this.startAngle.degrees();
  7015. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7016. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7017. // angles correction
  7018. if (a2 - a1 > +180.0)
  7019. a2 -= 360.0;
  7020. if (a2 - a1 < -180.0)
  7021. a2 += 360.0;
  7022. if (a3 - a2 > +180.0)
  7023. a3 -= 360.0;
  7024. if (a3 - a2 < -180.0)
  7025. a3 += 360.0;
  7026. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7027. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7028. }
  7029. return Arc2;
  7030. }());
  7031. BABYLON.Arc2 = Arc2;
  7032. var Path2 = /** @class */ (function () {
  7033. /**
  7034. * Creates a Path2 object from the starting 2D coordinates x and y.
  7035. */
  7036. function Path2(x, y) {
  7037. this._points = new Array();
  7038. this._length = 0.0;
  7039. this.closed = false;
  7040. this._points.push(new Vector2(x, y));
  7041. }
  7042. /**
  7043. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7044. * Returns the updated Path2.
  7045. */
  7046. Path2.prototype.addLineTo = function (x, y) {
  7047. if (this.closed) {
  7048. return this;
  7049. }
  7050. var newPoint = new Vector2(x, y);
  7051. var previousPoint = this._points[this._points.length - 1];
  7052. this._points.push(newPoint);
  7053. this._length += newPoint.subtract(previousPoint).length();
  7054. return this;
  7055. };
  7056. /**
  7057. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7061. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7062. if (this.closed) {
  7063. return this;
  7064. }
  7065. var startPoint = this._points[this._points.length - 1];
  7066. var midPoint = new Vector2(midX, midY);
  7067. var endPoint = new Vector2(endX, endY);
  7068. var arc = new Arc2(startPoint, midPoint, endPoint);
  7069. var increment = arc.angle.radians() / numberOfSegments;
  7070. if (arc.orientation === Orientation.CW)
  7071. increment *= -1;
  7072. var currentAngle = arc.startAngle.radians() + increment;
  7073. for (var i = 0; i < numberOfSegments; i++) {
  7074. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7075. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7076. this.addLineTo(x, y);
  7077. currentAngle += increment;
  7078. }
  7079. return this;
  7080. };
  7081. /**
  7082. * Closes the Path2.
  7083. * Returns the Path2.
  7084. */
  7085. Path2.prototype.close = function () {
  7086. this.closed = true;
  7087. return this;
  7088. };
  7089. /**
  7090. * Returns the Path2 total length (float).
  7091. */
  7092. Path2.prototype.length = function () {
  7093. var result = this._length;
  7094. if (!this.closed) {
  7095. var lastPoint = this._points[this._points.length - 1];
  7096. var firstPoint = this._points[0];
  7097. result += (firstPoint.subtract(lastPoint).length());
  7098. }
  7099. return result;
  7100. };
  7101. /**
  7102. * Returns the Path2 internal array of points.
  7103. */
  7104. Path2.prototype.getPoints = function () {
  7105. return this._points;
  7106. };
  7107. /**
  7108. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7109. */
  7110. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7111. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7112. return Vector2.Zero();
  7113. }
  7114. var lengthPosition = normalizedLengthPosition * this.length();
  7115. var previousOffset = 0;
  7116. for (var i = 0; i < this._points.length; i++) {
  7117. var j = (i + 1) % this._points.length;
  7118. var a = this._points[i];
  7119. var b = this._points[j];
  7120. var bToA = b.subtract(a);
  7121. var nextOffset = (bToA.length() + previousOffset);
  7122. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7123. var dir = bToA.normalize();
  7124. var localOffset = lengthPosition - previousOffset;
  7125. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7126. }
  7127. previousOffset = nextOffset;
  7128. }
  7129. return Vector2.Zero();
  7130. };
  7131. /**
  7132. * Returns a new Path2 starting at the coordinates (x, y).
  7133. */
  7134. Path2.StartingAt = function (x, y) {
  7135. return new Path2(x, y);
  7136. };
  7137. return Path2;
  7138. }());
  7139. BABYLON.Path2 = Path2;
  7140. var Path3D = /** @class */ (function () {
  7141. /**
  7142. * new Path3D(path, normal, raw)
  7143. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7144. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7145. * path : an array of Vector3, the curve axis of the Path3D
  7146. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7147. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7148. */
  7149. function Path3D(path, firstNormal, raw) {
  7150. if (firstNormal === void 0) { firstNormal = null; }
  7151. this.path = path;
  7152. this._curve = new Array();
  7153. this._distances = new Array();
  7154. this._tangents = new Array();
  7155. this._normals = new Array();
  7156. this._binormals = new Array();
  7157. for (var p = 0; p < path.length; p++) {
  7158. this._curve[p] = path[p].clone(); // hard copy
  7159. }
  7160. this._raw = raw || false;
  7161. this._compute(firstNormal);
  7162. }
  7163. /**
  7164. * Returns the Path3D array of successive Vector3 designing its curve.
  7165. */
  7166. Path3D.prototype.getCurve = function () {
  7167. return this._curve;
  7168. };
  7169. /**
  7170. * Returns an array populated with tangent vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getTangents = function () {
  7173. return this._tangents;
  7174. };
  7175. /**
  7176. * Returns an array populated with normal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getNormals = function () {
  7179. return this._normals;
  7180. };
  7181. /**
  7182. * Returns an array populated with binormal vectors on each Path3D curve point.
  7183. */
  7184. Path3D.prototype.getBinormals = function () {
  7185. return this._binormals;
  7186. };
  7187. /**
  7188. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7189. */
  7190. Path3D.prototype.getDistances = function () {
  7191. return this._distances;
  7192. };
  7193. /**
  7194. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7195. * Returns the same object updated.
  7196. */
  7197. Path3D.prototype.update = function (path, firstNormal) {
  7198. if (firstNormal === void 0) { firstNormal = null; }
  7199. for (var p = 0; p < path.length; p++) {
  7200. this._curve[p].x = path[p].x;
  7201. this._curve[p].y = path[p].y;
  7202. this._curve[p].z = path[p].z;
  7203. }
  7204. this._compute(firstNormal);
  7205. return this;
  7206. };
  7207. // private function compute() : computes tangents, normals and binormals
  7208. Path3D.prototype._compute = function (firstNormal) {
  7209. var l = this._curve.length;
  7210. // first and last tangents
  7211. this._tangents[0] = this._getFirstNonNullVector(0);
  7212. if (!this._raw) {
  7213. this._tangents[0].normalize();
  7214. }
  7215. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7216. if (!this._raw) {
  7217. this._tangents[l - 1].normalize();
  7218. }
  7219. // normals and binormals at first point : arbitrary vector with _normalVector()
  7220. var tg0 = this._tangents[0];
  7221. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7222. this._normals[0] = pp0;
  7223. if (!this._raw) {
  7224. this._normals[0].normalize();
  7225. }
  7226. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7227. if (!this._raw) {
  7228. this._binormals[0].normalize();
  7229. }
  7230. this._distances[0] = 0.0;
  7231. // normals and binormals : next points
  7232. var prev; // previous vector (segment)
  7233. var cur; // current vector (segment)
  7234. var curTang; // current tangent
  7235. // previous normal
  7236. var prevBinor; // previous binormal
  7237. for (var i = 1; i < l; i++) {
  7238. // tangents
  7239. prev = this._getLastNonNullVector(i);
  7240. if (i < l - 1) {
  7241. cur = this._getFirstNonNullVector(i);
  7242. this._tangents[i] = prev.add(cur);
  7243. this._tangents[i].normalize();
  7244. }
  7245. this._distances[i] = this._distances[i - 1] + prev.length();
  7246. // normals and binormals
  7247. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7248. curTang = this._tangents[i];
  7249. prevBinor = this._binormals[i - 1];
  7250. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7251. if (!this._raw) {
  7252. this._normals[i].normalize();
  7253. }
  7254. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7255. if (!this._raw) {
  7256. this._binormals[i].normalize();
  7257. }
  7258. }
  7259. };
  7260. // private function getFirstNonNullVector(index)
  7261. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7262. Path3D.prototype._getFirstNonNullVector = function (index) {
  7263. var i = 1;
  7264. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7265. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7266. i++;
  7267. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7268. }
  7269. return nNVector;
  7270. };
  7271. // private function getLastNonNullVector(index)
  7272. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7273. Path3D.prototype._getLastNonNullVector = function (index) {
  7274. var i = 1;
  7275. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7276. while (nLVector.length() === 0 && index > i + 1) {
  7277. i++;
  7278. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7279. }
  7280. return nLVector;
  7281. };
  7282. // private function normalVector(v0, vt, va) :
  7283. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7284. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7285. Path3D.prototype._normalVector = function (v0, vt, va) {
  7286. var normal0;
  7287. var tgl = vt.length();
  7288. if (tgl === 0.0) {
  7289. tgl = 1.0;
  7290. }
  7291. if (va === undefined || va === null) {
  7292. var point;
  7293. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7294. point = new Vector3(0.0, -1.0, 0.0);
  7295. }
  7296. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7297. point = new Vector3(1.0, 0.0, 0.0);
  7298. }
  7299. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7300. point = new Vector3(0.0, 0.0, 1.0);
  7301. }
  7302. else {
  7303. point = Vector3.Zero();
  7304. }
  7305. normal0 = Vector3.Cross(vt, point);
  7306. }
  7307. else {
  7308. normal0 = Vector3.Cross(vt, va);
  7309. Vector3.CrossToRef(normal0, vt, normal0);
  7310. }
  7311. normal0.normalize();
  7312. return normal0;
  7313. };
  7314. return Path3D;
  7315. }());
  7316. BABYLON.Path3D = Path3D;
  7317. var Curve3 = /** @class */ (function () {
  7318. /**
  7319. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7320. * A Curve3 is designed from a series of successive Vector3.
  7321. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7322. */
  7323. function Curve3(points) {
  7324. this._length = 0.0;
  7325. this._points = points;
  7326. this._length = this._computeLength(points);
  7327. }
  7328. /**
  7329. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7330. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7331. * @param v1 (Vector3) the control point
  7332. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7333. * @param nbPoints (integer) the wanted number of points in the curve
  7334. */
  7335. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7336. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7337. var bez = new Array();
  7338. var equation = function (t, val0, val1, val2) {
  7339. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7340. return res;
  7341. };
  7342. for (var i = 0; i <= nbPoints; i++) {
  7343. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7344. }
  7345. return new Curve3(bez);
  7346. };
  7347. /**
  7348. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7349. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7350. * @param v1 (Vector3) the first control point
  7351. * @param v2 (Vector3) the second control point
  7352. * @param v3 (Vector3) the end point of the Cubic Bezier
  7353. * @param nbPoints (integer) the wanted number of points in the curve
  7354. */
  7355. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7356. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7357. var bez = new Array();
  7358. var equation = function (t, val0, val1, val2, val3) {
  7359. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7360. return res;
  7361. };
  7362. for (var i = 0; i <= nbPoints; i++) {
  7363. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7364. }
  7365. return new Curve3(bez);
  7366. };
  7367. /**
  7368. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7369. * @param p1 (Vector3) the origin point of the Hermite Spline
  7370. * @param t1 (Vector3) the tangent vector at the origin point
  7371. * @param p2 (Vector3) the end point of the Hermite Spline
  7372. * @param t2 (Vector3) the tangent vector at the end point
  7373. * @param nbPoints (integer) the wanted number of points in the curve
  7374. */
  7375. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7376. var hermite = new Array();
  7377. var step = 1.0 / nbPoints;
  7378. for (var i = 0; i <= nbPoints; i++) {
  7379. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7380. }
  7381. return new Curve3(hermite);
  7382. };
  7383. /**
  7384. * Returns a Curve3 object along a CatmullRom Spline curve :
  7385. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7386. * @param nbPoints (integer) the wanted number of points between each curve control points
  7387. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7388. */
  7389. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7390. var catmullRom = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. var amount = 0.0;
  7393. if (closed) {
  7394. var pointsCount = points.length;
  7395. for (var i = 0; i < pointsCount; i++) {
  7396. amount = 0;
  7397. for (var c = 0; c < nbPoints; c++) {
  7398. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7399. amount += step;
  7400. }
  7401. }
  7402. catmullRom.push(catmullRom[0]);
  7403. }
  7404. else {
  7405. var totalPoints = new Array();
  7406. totalPoints.push(points[0].clone());
  7407. Array.prototype.push.apply(totalPoints, points);
  7408. totalPoints.push(points[points.length - 1].clone());
  7409. for (var i = 0; i < totalPoints.length - 3; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. i--;
  7417. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7418. }
  7419. return new Curve3(catmullRom);
  7420. };
  7421. /**
  7422. * Returns the Curve3 stored array of successive Vector3
  7423. */
  7424. Curve3.prototype.getPoints = function () {
  7425. return this._points;
  7426. };
  7427. /**
  7428. * Returns the computed length (float) of the curve.
  7429. */
  7430. Curve3.prototype.length = function () {
  7431. return this._length;
  7432. };
  7433. /**
  7434. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7435. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7436. * curveA and curveB keep unchanged.
  7437. */
  7438. Curve3.prototype.continue = function (curve) {
  7439. var lastPoint = this._points[this._points.length - 1];
  7440. var continuedPoints = this._points.slice();
  7441. var curvePoints = curve.getPoints();
  7442. for (var i = 1; i < curvePoints.length; i++) {
  7443. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7444. }
  7445. var continuedCurve = new Curve3(continuedPoints);
  7446. return continuedCurve;
  7447. };
  7448. Curve3.prototype._computeLength = function (path) {
  7449. var l = 0;
  7450. for (var i = 1; i < path.length; i++) {
  7451. l += (path[i].subtract(path[i - 1])).length();
  7452. }
  7453. return l;
  7454. };
  7455. return Curve3;
  7456. }());
  7457. BABYLON.Curve3 = Curve3;
  7458. // Vertex formats
  7459. var PositionNormalVertex = /** @class */ (function () {
  7460. function PositionNormalVertex(position, normal) {
  7461. if (position === void 0) { position = Vector3.Zero(); }
  7462. if (normal === void 0) { normal = Vector3.Up(); }
  7463. this.position = position;
  7464. this.normal = normal;
  7465. }
  7466. PositionNormalVertex.prototype.clone = function () {
  7467. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7468. };
  7469. return PositionNormalVertex;
  7470. }());
  7471. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7472. var PositionNormalTextureVertex = /** @class */ (function () {
  7473. function PositionNormalTextureVertex(position, normal, uv) {
  7474. if (position === void 0) { position = Vector3.Zero(); }
  7475. if (normal === void 0) { normal = Vector3.Up(); }
  7476. if (uv === void 0) { uv = Vector2.Zero(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. this.uv = uv;
  7480. }
  7481. PositionNormalTextureVertex.prototype.clone = function () {
  7482. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7483. };
  7484. return PositionNormalTextureVertex;
  7485. }());
  7486. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7487. // Temporary pre-allocated objects for engine internal use
  7488. // usage in any internal function :
  7489. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7490. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7491. var Tmp = /** @class */ (function () {
  7492. function Tmp() {
  7493. }
  7494. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7495. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7496. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7497. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7498. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7499. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7500. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7501. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7502. Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7505. return Tmp;
  7506. }());
  7507. BABYLON.Tmp = Tmp;
  7508. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7509. var MathTmp = /** @class */ (function () {
  7510. function MathTmp() {
  7511. }
  7512. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7513. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7514. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7515. return MathTmp;
  7516. }());
  7517. })(BABYLON || (BABYLON = {}));
  7518. //# sourceMappingURL=babylon.math.js.map
  7519. var BABYLON;
  7520. (function (BABYLON) {
  7521. var Scalar = /** @class */ (function () {
  7522. function Scalar() {
  7523. }
  7524. /**
  7525. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7526. */
  7527. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7528. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7529. var num = a - b;
  7530. return -epsilon <= num && num <= epsilon;
  7531. };
  7532. /**
  7533. * Returns a string : the upper case translation of the number i to hexadecimal.
  7534. */
  7535. Scalar.ToHex = function (i) {
  7536. var str = i.toString(16);
  7537. if (i <= 15) {
  7538. return ("0" + str).toUpperCase();
  7539. }
  7540. return str.toUpperCase();
  7541. };
  7542. /**
  7543. * Returns -1 if value is negative and +1 is value is positive.
  7544. * Returns the value itself if it's equal to zero.
  7545. */
  7546. Scalar.Sign = function (value) {
  7547. value = +value; // convert to a number
  7548. if (value === 0 || isNaN(value))
  7549. return value;
  7550. return value > 0 ? 1 : -1;
  7551. };
  7552. /**
  7553. * Returns the value itself if it's between min and max.
  7554. * Returns min if the value is lower than min.
  7555. * Returns max if the value is greater than max.
  7556. */
  7557. Scalar.Clamp = function (value, min, max) {
  7558. if (min === void 0) { min = 0; }
  7559. if (max === void 0) { max = 1; }
  7560. return Math.min(max, Math.max(min, value));
  7561. };
  7562. /**
  7563. * Returns the log2 of value.
  7564. */
  7565. Scalar.Log2 = function (value) {
  7566. return Math.log(value) * Math.LOG2E;
  7567. };
  7568. /**
  7569. * Loops the value, so that it is never larger than length and never smaller than 0.
  7570. *
  7571. * This is similar to the modulo operator but it works with floating point numbers.
  7572. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7573. * With t = 5 and length = 2.5, the result would be 0.0.
  7574. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7575. */
  7576. Scalar.Repeat = function (value, length) {
  7577. return value - Math.floor(value / length) * length;
  7578. };
  7579. /**
  7580. * Normalize the value between 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Normalize = function (value, min, max) {
  7583. return (value - min) / (max - min);
  7584. };
  7585. /**
  7586. * Denormalize the value from 0.0 and 1.0 using min and max values
  7587. */
  7588. Scalar.Denormalize = function (normalized, min, max) {
  7589. return (normalized * (max - min) + min);
  7590. };
  7591. /**
  7592. * Calculates the shortest difference between two given angles given in degrees.
  7593. */
  7594. Scalar.DeltaAngle = function (current, target) {
  7595. var num = Scalar.Repeat(target - current, 360.0);
  7596. if (num > 180.0) {
  7597. num -= 360.0;
  7598. }
  7599. return num;
  7600. };
  7601. /**
  7602. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7603. *
  7604. * The returned value will move back and forth between 0 and length
  7605. */
  7606. Scalar.PingPong = function (tx, length) {
  7607. var t = Scalar.Repeat(tx, length * 2.0);
  7608. return length - Math.abs(t - length);
  7609. };
  7610. /**
  7611. * Interpolates between min and max with smoothing at the limits.
  7612. *
  7613. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7614. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7615. */
  7616. Scalar.SmoothStep = function (from, to, tx) {
  7617. var t = Scalar.Clamp(tx);
  7618. t = -2.0 * t * t * t + 3.0 * t * t;
  7619. return to * t + from * (1.0 - t);
  7620. };
  7621. /**
  7622. * Moves a value current towards target.
  7623. *
  7624. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7625. * Negative values of maxDelta pushes the value away from target.
  7626. */
  7627. Scalar.MoveTowards = function (current, target, maxDelta) {
  7628. var result = 0;
  7629. if (Math.abs(target - current) <= maxDelta) {
  7630. result = target;
  7631. }
  7632. else {
  7633. result = current + Scalar.Sign(target - current) * maxDelta;
  7634. }
  7635. return result;
  7636. };
  7637. /**
  7638. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7639. *
  7640. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7641. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7642. */
  7643. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7644. var num = Scalar.DeltaAngle(current, target);
  7645. var result = 0;
  7646. if (-maxDelta < num && num < maxDelta) {
  7647. result = target;
  7648. }
  7649. else {
  7650. target = current + num;
  7651. result = Scalar.MoveTowards(current, target, maxDelta);
  7652. }
  7653. return result;
  7654. };
  7655. /**
  7656. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7657. */
  7658. Scalar.Lerp = function (start, end, amount) {
  7659. return start + ((end - start) * amount);
  7660. };
  7661. /**
  7662. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7663. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7664. */
  7665. Scalar.LerpAngle = function (start, end, amount) {
  7666. var num = Scalar.Repeat(end - start, 360.0);
  7667. if (num > 180.0) {
  7668. num -= 360.0;
  7669. }
  7670. return start + num * Scalar.Clamp(amount);
  7671. };
  7672. /**
  7673. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7674. */
  7675. Scalar.InverseLerp = function (a, b, value) {
  7676. var result = 0;
  7677. if (a != b) {
  7678. result = Scalar.Clamp((value - a) / (b - a));
  7679. }
  7680. else {
  7681. result = 0.0;
  7682. }
  7683. return result;
  7684. };
  7685. /**
  7686. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7687. */
  7688. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7689. var squared = amount * amount;
  7690. var cubed = amount * squared;
  7691. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7692. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7693. var part3 = (cubed - (2.0 * squared)) + amount;
  7694. var part4 = cubed - squared;
  7695. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7696. };
  7697. /**
  7698. * Returns a random float number between and min and max values
  7699. */
  7700. Scalar.RandomRange = function (min, max) {
  7701. if (min === max)
  7702. return min;
  7703. return ((Math.random() * (max - min)) + min);
  7704. };
  7705. /**
  7706. * This function returns percentage of a number in a given range.
  7707. *
  7708. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7709. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7710. */
  7711. Scalar.RangeToPercent = function (number, min, max) {
  7712. return ((number - min) / (max - min));
  7713. };
  7714. /**
  7715. * This function returns number that corresponds to the percentage in a given range.
  7716. *
  7717. * PercentToRange(0.34,0,100) will return 34.
  7718. */
  7719. Scalar.PercentToRange = function (percent, min, max) {
  7720. return ((max - min) * percent + min);
  7721. };
  7722. /**
  7723. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7724. * @param angle The angle to normalize in radian.
  7725. * @return The converted angle.
  7726. */
  7727. Scalar.NormalizeRadians = function (angle) {
  7728. // More precise but slower version kept for reference.
  7729. // angle = angle % Tools.TwoPi;
  7730. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7731. //if (angle > Math.PI) {
  7732. // angle -= Tools.TwoPi;
  7733. //}
  7734. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7735. return angle;
  7736. };
  7737. /**
  7738. * Two pi constants convenient for computation.
  7739. */
  7740. Scalar.TwoPi = Math.PI * 2;
  7741. return Scalar;
  7742. }());
  7743. BABYLON.Scalar = Scalar;
  7744. })(BABYLON || (BABYLON = {}));
  7745. //# sourceMappingURL=babylon.math.scalar.js.map
  7746. //# sourceMappingURL=babylon.mixins.js.map
  7747. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7748. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7749. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7750. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7751. //# sourceMappingURL=babylon.webgl2.js.map
  7752. var BABYLON;
  7753. (function (BABYLON) {
  7754. var __decoratorInitialStore = {};
  7755. var __mergedStore = {};
  7756. var _copySource = function (creationFunction, source, instanciate) {
  7757. var destination = creationFunction();
  7758. // Tags
  7759. if (BABYLON.Tags) {
  7760. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7761. }
  7762. var classStore = getMergedStore(destination);
  7763. // Properties
  7764. for (var property in classStore) {
  7765. var propertyDescriptor = classStore[property];
  7766. var sourceProperty = source[property];
  7767. var propertyType = propertyDescriptor.type;
  7768. if (sourceProperty !== undefined && sourceProperty !== null) {
  7769. switch (propertyType) {
  7770. case 0: // Value
  7771. case 6: // Mesh reference
  7772. case 11: // Camera reference
  7773. destination[property] = sourceProperty;
  7774. break;
  7775. case 1: // Texture
  7776. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7777. break;
  7778. case 2: // Color3
  7779. case 3: // FresnelParameters
  7780. case 4: // Vector2
  7781. case 5: // Vector3
  7782. case 7: // Color Curves
  7783. case 10: // Quaternion
  7784. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7785. break;
  7786. }
  7787. }
  7788. }
  7789. return destination;
  7790. };
  7791. function getDirectStore(target) {
  7792. var classKey = target.getClassName();
  7793. if (!__decoratorInitialStore[classKey]) {
  7794. __decoratorInitialStore[classKey] = {};
  7795. }
  7796. return __decoratorInitialStore[classKey];
  7797. }
  7798. /**
  7799. * Return the list of properties flagged as serializable
  7800. * @param target: host object
  7801. */
  7802. function getMergedStore(target) {
  7803. var classKey = target.getClassName();
  7804. if (__mergedStore[classKey]) {
  7805. return __mergedStore[classKey];
  7806. }
  7807. __mergedStore[classKey] = {};
  7808. var store = __mergedStore[classKey];
  7809. var currentTarget = target;
  7810. var currentKey = classKey;
  7811. while (currentKey) {
  7812. var initialStore = __decoratorInitialStore[currentKey];
  7813. for (var property in initialStore) {
  7814. store[property] = initialStore[property];
  7815. }
  7816. var parent_1 = void 0;
  7817. var done = false;
  7818. do {
  7819. parent_1 = Object.getPrototypeOf(currentTarget);
  7820. if (!parent_1.getClassName) {
  7821. done = true;
  7822. break;
  7823. }
  7824. if (parent_1.getClassName() !== currentKey) {
  7825. break;
  7826. }
  7827. currentTarget = parent_1;
  7828. } while (parent_1);
  7829. if (done) {
  7830. break;
  7831. }
  7832. currentKey = parent_1.getClassName();
  7833. currentTarget = parent_1;
  7834. }
  7835. return store;
  7836. }
  7837. function generateSerializableMember(type, sourceName) {
  7838. return function (target, propertyKey) {
  7839. var classStore = getDirectStore(target);
  7840. if (!classStore[propertyKey]) {
  7841. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7842. }
  7843. };
  7844. }
  7845. function generateExpandMember(setCallback, targetKey) {
  7846. if (targetKey === void 0) { targetKey = null; }
  7847. return function (target, propertyKey) {
  7848. var key = targetKey || ("_" + propertyKey);
  7849. Object.defineProperty(target, propertyKey, {
  7850. get: function () {
  7851. return this[key];
  7852. },
  7853. set: function (value) {
  7854. if (this[key] === value) {
  7855. return;
  7856. }
  7857. this[key] = value;
  7858. target[setCallback].apply(this);
  7859. },
  7860. enumerable: true,
  7861. configurable: true
  7862. });
  7863. };
  7864. }
  7865. function expandToProperty(callback, targetKey) {
  7866. if (targetKey === void 0) { targetKey = null; }
  7867. return generateExpandMember(callback, targetKey);
  7868. }
  7869. BABYLON.expandToProperty = expandToProperty;
  7870. function serialize(sourceName) {
  7871. return generateSerializableMember(0, sourceName); // value member
  7872. }
  7873. BABYLON.serialize = serialize;
  7874. function serializeAsTexture(sourceName) {
  7875. return generateSerializableMember(1, sourceName); // texture member
  7876. }
  7877. BABYLON.serializeAsTexture = serializeAsTexture;
  7878. function serializeAsColor3(sourceName) {
  7879. return generateSerializableMember(2, sourceName); // color3 member
  7880. }
  7881. BABYLON.serializeAsColor3 = serializeAsColor3;
  7882. function serializeAsFresnelParameters(sourceName) {
  7883. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7884. }
  7885. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7886. function serializeAsVector2(sourceName) {
  7887. return generateSerializableMember(4, sourceName); // vector2 member
  7888. }
  7889. BABYLON.serializeAsVector2 = serializeAsVector2;
  7890. function serializeAsVector3(sourceName) {
  7891. return generateSerializableMember(5, sourceName); // vector3 member
  7892. }
  7893. BABYLON.serializeAsVector3 = serializeAsVector3;
  7894. function serializeAsMeshReference(sourceName) {
  7895. return generateSerializableMember(6, sourceName); // mesh reference member
  7896. }
  7897. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7898. function serializeAsColorCurves(sourceName) {
  7899. return generateSerializableMember(7, sourceName); // color curves
  7900. }
  7901. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7902. function serializeAsColor4(sourceName) {
  7903. return generateSerializableMember(8, sourceName); // color 4
  7904. }
  7905. BABYLON.serializeAsColor4 = serializeAsColor4;
  7906. function serializeAsImageProcessingConfiguration(sourceName) {
  7907. return generateSerializableMember(9, sourceName); // image processing
  7908. }
  7909. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7910. function serializeAsQuaternion(sourceName) {
  7911. return generateSerializableMember(10, sourceName); // quaternion member
  7912. }
  7913. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7914. /**
  7915. * Decorator used to define property that can be serialized as reference to a camera
  7916. * @param sourceName defines the name of the property to decorate
  7917. */
  7918. function serializeAsCameraReference(sourceName) {
  7919. return generateSerializableMember(11, sourceName); // camera reference member
  7920. }
  7921. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7922. var SerializationHelper = /** @class */ (function () {
  7923. function SerializationHelper() {
  7924. }
  7925. SerializationHelper.Serialize = function (entity, serializationObject) {
  7926. if (!serializationObject) {
  7927. serializationObject = {};
  7928. }
  7929. // Tags
  7930. if (BABYLON.Tags) {
  7931. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7932. }
  7933. var serializedProperties = getMergedStore(entity);
  7934. // Properties
  7935. for (var property in serializedProperties) {
  7936. var propertyDescriptor = serializedProperties[property];
  7937. var targetPropertyName = propertyDescriptor.sourceName || property;
  7938. var propertyType = propertyDescriptor.type;
  7939. var sourceProperty = entity[property];
  7940. if (sourceProperty !== undefined && sourceProperty !== null) {
  7941. switch (propertyType) {
  7942. case 0: // Value
  7943. serializationObject[targetPropertyName] = sourceProperty;
  7944. break;
  7945. case 1: // Texture
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 2: // Color3
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 3: // FresnelParameters
  7952. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7953. break;
  7954. case 4: // Vector2
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 5: // Vector3
  7958. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7959. break;
  7960. case 6: // Mesh reference
  7961. serializationObject[targetPropertyName] = sourceProperty.id;
  7962. break;
  7963. case 7: // Color Curves
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 8: // Color 4
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 9: // Image Processing
  7970. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7971. break;
  7972. case 10: // Quaternion
  7973. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7974. break;
  7975. case 11: // Camera reference
  7976. serializationObject[targetPropertyName] = sourceProperty.id;
  7977. break;
  7978. }
  7979. }
  7980. }
  7981. return serializationObject;
  7982. };
  7983. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7984. if (rootUrl === void 0) { rootUrl = null; }
  7985. var destination = creationFunction();
  7986. if (!rootUrl) {
  7987. rootUrl = "";
  7988. }
  7989. // Tags
  7990. if (BABYLON.Tags) {
  7991. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7992. }
  7993. var classStore = getMergedStore(destination);
  7994. // Properties
  7995. for (var property in classStore) {
  7996. var propertyDescriptor = classStore[property];
  7997. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7998. var propertyType = propertyDescriptor.type;
  7999. if (sourceProperty !== undefined && sourceProperty !== null) {
  8000. var dest = destination;
  8001. switch (propertyType) {
  8002. case 0: // Value
  8003. dest[property] = sourceProperty;
  8004. break;
  8005. case 1: // Texture
  8006. if (scene) {
  8007. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8008. }
  8009. break;
  8010. case 2: // Color3
  8011. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8012. break;
  8013. case 3: // FresnelParameters
  8014. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8015. break;
  8016. case 4: // Vector2
  8017. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8018. break;
  8019. case 5: // Vector3
  8020. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8021. break;
  8022. case 6: // Mesh reference
  8023. if (scene) {
  8024. dest[property] = scene.getLastMeshByID(sourceProperty);
  8025. }
  8026. break;
  8027. case 7: // Color Curves
  8028. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8029. break;
  8030. case 8: // Color 4
  8031. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8032. break;
  8033. case 9: // Image Processing
  8034. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8035. break;
  8036. case 10: // Quaternion
  8037. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8038. break;
  8039. case 11: // Camera reference
  8040. if (scene) {
  8041. dest[property] = scene.getCameraByID(sourceProperty);
  8042. }
  8043. break;
  8044. }
  8045. }
  8046. }
  8047. return destination;
  8048. };
  8049. SerializationHelper.Clone = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, false);
  8051. };
  8052. SerializationHelper.Instanciate = function (creationFunction, source) {
  8053. return _copySource(creationFunction, source, true);
  8054. };
  8055. return SerializationHelper;
  8056. }());
  8057. BABYLON.SerializationHelper = SerializationHelper;
  8058. })(BABYLON || (BABYLON = {}));
  8059. //# sourceMappingURL=babylon.decorators.js.map
  8060. var BABYLON;
  8061. (function (BABYLON) {
  8062. /**
  8063. * Wrapper class for promise with external resolve and reject.
  8064. */
  8065. var Deferred = /** @class */ (function () {
  8066. /**
  8067. * Constructor for this deferred object.
  8068. */
  8069. function Deferred() {
  8070. var _this = this;
  8071. this.promise = new Promise(function (resolve, reject) {
  8072. _this._resolve = resolve;
  8073. _this._reject = reject;
  8074. });
  8075. }
  8076. Object.defineProperty(Deferred.prototype, "resolve", {
  8077. /**
  8078. * The resolve method of the promise associated with this deferred object.
  8079. */
  8080. get: function () {
  8081. return this._resolve;
  8082. },
  8083. enumerable: true,
  8084. configurable: true
  8085. });
  8086. Object.defineProperty(Deferred.prototype, "reject", {
  8087. /**
  8088. * The reject method of the promise associated with this deferred object.
  8089. */
  8090. get: function () {
  8091. return this._reject;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. return Deferred;
  8097. }());
  8098. BABYLON.Deferred = Deferred;
  8099. })(BABYLON || (BABYLON = {}));
  8100. //# sourceMappingURL=babylon.deferred.js.map
  8101. var BABYLON;
  8102. (function (BABYLON) {
  8103. /**
  8104. * A class serves as a medium between the observable and its observers
  8105. */
  8106. var EventState = /** @class */ (function () {
  8107. /**
  8108. * Create a new EventState
  8109. * @param mask defines the mask associated with this state
  8110. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8111. * @param target defines the original target of the state
  8112. * @param currentTarget defines the current target of the state
  8113. */
  8114. function EventState(mask, skipNextObservers, target, currentTarget) {
  8115. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8116. this.initalize(mask, skipNextObservers, target, currentTarget);
  8117. }
  8118. /**
  8119. * Initialize the current event state
  8120. * @param mask defines the mask associated with this state
  8121. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8122. * @param target defines the original target of the state
  8123. * @param currentTarget defines the current target of the state
  8124. * @returns the current event state
  8125. */
  8126. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8127. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8128. this.mask = mask;
  8129. this.skipNextObservers = skipNextObservers;
  8130. this.target = target;
  8131. this.currentTarget = currentTarget;
  8132. return this;
  8133. };
  8134. return EventState;
  8135. }());
  8136. BABYLON.EventState = EventState;
  8137. /**
  8138. * Represent an Observer registered to a given Observable object.
  8139. */
  8140. var Observer = /** @class */ (function () {
  8141. /**
  8142. * Creates a new observer
  8143. * @param callback defines the callback to call when the observer is notified
  8144. * @param mask defines the mask of the observer (used to filter notifications)
  8145. * @param scope defines the current scope used to restore the JS context
  8146. */
  8147. function Observer(
  8148. /**
  8149. * Defines the callback to call when the observer is notified
  8150. */
  8151. callback,
  8152. /**
  8153. * Defines the mask of the observer (used to filter notifications)
  8154. */
  8155. mask,
  8156. /**
  8157. * Defines the current scope used to restore the JS context
  8158. */
  8159. scope) {
  8160. if (scope === void 0) { scope = null; }
  8161. this.callback = callback;
  8162. this.mask = mask;
  8163. this.scope = scope;
  8164. /** @hidden */
  8165. this._willBeUnregistered = false;
  8166. /**
  8167. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8168. */
  8169. this.unregisterOnNextCall = false;
  8170. }
  8171. return Observer;
  8172. }());
  8173. BABYLON.Observer = Observer;
  8174. /**
  8175. * Represent a list of observers registered to multiple Observables object.
  8176. */
  8177. var MultiObserver = /** @class */ (function () {
  8178. function MultiObserver() {
  8179. }
  8180. /**
  8181. * Release associated resources
  8182. */
  8183. MultiObserver.prototype.dispose = function () {
  8184. if (this._observers && this._observables) {
  8185. for (var index = 0; index < this._observers.length; index++) {
  8186. this._observables[index].remove(this._observers[index]);
  8187. }
  8188. }
  8189. this._observers = null;
  8190. this._observables = null;
  8191. };
  8192. /**
  8193. * Raise a callback when one of the observable will notify
  8194. * @param observables defines a list of observables to watch
  8195. * @param callback defines the callback to call on notification
  8196. * @param mask defines the mask used to filter notifications
  8197. * @param scope defines the current scope used to restore the JS context
  8198. * @returns the new MultiObserver
  8199. */
  8200. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8201. if (mask === void 0) { mask = -1; }
  8202. if (scope === void 0) { scope = null; }
  8203. var result = new MultiObserver();
  8204. result._observers = new Array();
  8205. result._observables = observables;
  8206. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8207. var observable = observables_1[_i];
  8208. var observer = observable.add(callback, mask, false, scope);
  8209. if (observer) {
  8210. result._observers.push(observer);
  8211. }
  8212. }
  8213. return result;
  8214. };
  8215. return MultiObserver;
  8216. }());
  8217. BABYLON.MultiObserver = MultiObserver;
  8218. /**
  8219. * The Observable class is a simple implementation of the Observable pattern.
  8220. *
  8221. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8222. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8223. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8224. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8225. */
  8226. var Observable = /** @class */ (function () {
  8227. /**
  8228. * Creates a new observable
  8229. * @param onObserverAdded defines a callback to call when a new observer is added
  8230. */
  8231. function Observable(onObserverAdded) {
  8232. this._observers = new Array();
  8233. this._eventState = new EventState(0);
  8234. if (onObserverAdded) {
  8235. this._onObserverAdded = onObserverAdded;
  8236. }
  8237. }
  8238. /**
  8239. * Create a new Observer with the specified callback
  8240. * @param callback the callback that will be executed for that Observer
  8241. * @param mask the mask used to filter observers
  8242. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8243. * @param scope optional scope for the callback to be called from
  8244. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8245. * @returns the new observer created for the callback
  8246. */
  8247. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8248. if (mask === void 0) { mask = -1; }
  8249. if (insertFirst === void 0) { insertFirst = false; }
  8250. if (scope === void 0) { scope = null; }
  8251. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8252. if (!callback) {
  8253. return null;
  8254. }
  8255. var observer = new Observer(callback, mask, scope);
  8256. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8257. if (insertFirst) {
  8258. this._observers.unshift(observer);
  8259. }
  8260. else {
  8261. this._observers.push(observer);
  8262. }
  8263. if (this._onObserverAdded) {
  8264. this._onObserverAdded(observer);
  8265. }
  8266. return observer;
  8267. };
  8268. /**
  8269. * Create a new Observer with the specified callback and unregisters after the next notification
  8270. * @param callback the callback that will be executed for that Observer
  8271. * @returns the new observer created for the callback
  8272. */
  8273. Observable.prototype.addOnce = function (callback) {
  8274. return this.add(callback, undefined, undefined, undefined, true);
  8275. };
  8276. /**
  8277. * Remove an Observer from the Observable object
  8278. * @param observer the instance of the Observer to remove
  8279. * @returns false if it doesn't belong to this Observable
  8280. */
  8281. Observable.prototype.remove = function (observer) {
  8282. if (!observer) {
  8283. return false;
  8284. }
  8285. var index = this._observers.indexOf(observer);
  8286. if (index !== -1) {
  8287. this._deferUnregister(observer);
  8288. return true;
  8289. }
  8290. return false;
  8291. };
  8292. /**
  8293. * Remove a callback from the Observable object
  8294. * @param callback the callback to remove
  8295. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8296. * @returns false if it doesn't belong to this Observable
  8297. */
  8298. Observable.prototype.removeCallback = function (callback, scope) {
  8299. for (var index = 0; index < this._observers.length; index++) {
  8300. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8301. this._deferUnregister(this._observers[index]);
  8302. return true;
  8303. }
  8304. }
  8305. return false;
  8306. };
  8307. Observable.prototype._deferUnregister = function (observer) {
  8308. var _this = this;
  8309. observer.unregisterOnNextCall = false;
  8310. observer._willBeUnregistered = true;
  8311. BABYLON.Tools.SetImmediate(function () {
  8312. _this._remove(observer);
  8313. });
  8314. };
  8315. // This should only be called when not iterating over _observers to avoid callback skipping.
  8316. // Removes an observer from the _observer Array.
  8317. Observable.prototype._remove = function (observer) {
  8318. if (!observer) {
  8319. return false;
  8320. }
  8321. var index = this._observers.indexOf(observer);
  8322. if (index !== -1) {
  8323. this._observers.splice(index, 1);
  8324. return true;
  8325. }
  8326. return false;
  8327. };
  8328. /**
  8329. * Notify all Observers by calling their respective callback with the given data
  8330. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8331. * @param eventData defines the data to send to all observers
  8332. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8333. * @param target defines the original target of the state
  8334. * @param currentTarget defines the current target of the state
  8335. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8336. */
  8337. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8338. if (mask === void 0) { mask = -1; }
  8339. if (!this._observers.length) {
  8340. return true;
  8341. }
  8342. var state = this._eventState;
  8343. state.mask = mask;
  8344. state.target = target;
  8345. state.currentTarget = currentTarget;
  8346. state.skipNextObservers = false;
  8347. state.lastReturnValue = eventData;
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs._willBeUnregistered) {
  8351. continue;
  8352. }
  8353. if (obs.mask & mask) {
  8354. if (obs.scope) {
  8355. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8356. }
  8357. else {
  8358. state.lastReturnValue = obs.callback(eventData, state);
  8359. }
  8360. if (obs.unregisterOnNextCall) {
  8361. this._deferUnregister(obs);
  8362. }
  8363. }
  8364. if (state.skipNextObservers) {
  8365. return false;
  8366. }
  8367. }
  8368. return true;
  8369. };
  8370. /**
  8371. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8372. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8373. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8374. * and it is crucial that all callbacks will be executed.
  8375. * The order of the callbacks is kept, callbacks are not executed parallel.
  8376. *
  8377. * @param eventData The data to be sent to each callback
  8378. * @param mask is used to filter observers defaults to -1
  8379. * @param target defines the callback target (see EventState)
  8380. * @param currentTarget defines he current object in the bubbling phase
  8381. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8382. */
  8383. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8384. var _this = this;
  8385. if (mask === void 0) { mask = -1; }
  8386. // create an empty promise
  8387. var p = Promise.resolve(eventData);
  8388. // no observers? return this promise.
  8389. if (!this._observers.length) {
  8390. return p;
  8391. }
  8392. var state = this._eventState;
  8393. state.mask = mask;
  8394. state.target = target;
  8395. state.currentTarget = currentTarget;
  8396. state.skipNextObservers = false;
  8397. // execute one callback after another (not using Promise.all, the order is important)
  8398. this._observers.forEach(function (obs) {
  8399. if (state.skipNextObservers) {
  8400. return;
  8401. }
  8402. if (obs._willBeUnregistered) {
  8403. return;
  8404. }
  8405. if (obs.mask & mask) {
  8406. if (obs.scope) {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback.apply(obs.scope, [eventData, state]);
  8410. });
  8411. }
  8412. else {
  8413. p = p.then(function (lastReturnedValue) {
  8414. state.lastReturnValue = lastReturnedValue;
  8415. return obs.callback(eventData, state);
  8416. });
  8417. }
  8418. if (obs.unregisterOnNextCall) {
  8419. _this._deferUnregister(obs);
  8420. }
  8421. }
  8422. });
  8423. // return the eventData
  8424. return p.then(function () { return eventData; });
  8425. };
  8426. /**
  8427. * Notify a specific observer
  8428. * @param observer defines the observer to notify
  8429. * @param eventData defines the data to be sent to each callback
  8430. * @param mask is used to filter observers defaults to -1
  8431. */
  8432. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8433. if (mask === void 0) { mask = -1; }
  8434. var state = this._eventState;
  8435. state.mask = mask;
  8436. state.skipNextObservers = false;
  8437. observer.callback(eventData, state);
  8438. };
  8439. /**
  8440. * Gets a boolean indicating if the observable has at least one observer
  8441. * @returns true is the Observable has at least one Observer registered
  8442. */
  8443. Observable.prototype.hasObservers = function () {
  8444. return this._observers.length > 0;
  8445. };
  8446. /**
  8447. * Clear the list of observers
  8448. */
  8449. Observable.prototype.clear = function () {
  8450. this._observers = new Array();
  8451. this._onObserverAdded = null;
  8452. };
  8453. /**
  8454. * Clone the current observable
  8455. * @returns a new observable
  8456. */
  8457. Observable.prototype.clone = function () {
  8458. var result = new Observable();
  8459. result._observers = this._observers.slice(0);
  8460. return result;
  8461. };
  8462. /**
  8463. * Does this observable handles observer registered with a given mask
  8464. * @param mask defines the mask to be tested
  8465. * @return whether or not one observer registered with the given mask is handeled
  8466. **/
  8467. Observable.prototype.hasSpecificMask = function (mask) {
  8468. if (mask === void 0) { mask = -1; }
  8469. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8470. var obs = _a[_i];
  8471. if (obs.mask & mask || obs.mask === mask) {
  8472. return true;
  8473. }
  8474. }
  8475. return false;
  8476. };
  8477. return Observable;
  8478. }());
  8479. BABYLON.Observable = Observable;
  8480. })(BABYLON || (BABYLON = {}));
  8481. //# sourceMappingURL=babylon.observable.js.map
  8482. var BABYLON;
  8483. (function (BABYLON) {
  8484. var SmartArray = /** @class */ (function () {
  8485. function SmartArray(capacity) {
  8486. this.length = 0;
  8487. this.data = new Array(capacity);
  8488. this._id = SmartArray._GlobalId++;
  8489. }
  8490. SmartArray.prototype.push = function (value) {
  8491. this.data[this.length++] = value;
  8492. if (this.length > this.data.length) {
  8493. this.data.length *= 2;
  8494. }
  8495. };
  8496. SmartArray.prototype.forEach = function (func) {
  8497. for (var index = 0; index < this.length; index++) {
  8498. func(this.data[index]);
  8499. }
  8500. };
  8501. SmartArray.prototype.sort = function (compareFn) {
  8502. this.data.sort(compareFn);
  8503. };
  8504. SmartArray.prototype.reset = function () {
  8505. this.length = 0;
  8506. };
  8507. SmartArray.prototype.dispose = function () {
  8508. this.reset();
  8509. if (this.data) {
  8510. this.data.length = 0;
  8511. this.data = [];
  8512. }
  8513. };
  8514. SmartArray.prototype.concat = function (array) {
  8515. if (array.length === 0) {
  8516. return;
  8517. }
  8518. if (this.length + array.length > this.data.length) {
  8519. this.data.length = (this.length + array.length) * 2;
  8520. }
  8521. for (var index = 0; index < array.length; index++) {
  8522. this.data[this.length++] = (array.data || array)[index];
  8523. }
  8524. };
  8525. SmartArray.prototype.indexOf = function (value) {
  8526. var position = this.data.indexOf(value);
  8527. if (position >= this.length) {
  8528. return -1;
  8529. }
  8530. return position;
  8531. };
  8532. SmartArray.prototype.contains = function (value) {
  8533. return this.data.indexOf(value) !== -1;
  8534. };
  8535. // Statics
  8536. SmartArray._GlobalId = 0;
  8537. return SmartArray;
  8538. }());
  8539. BABYLON.SmartArray = SmartArray;
  8540. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8541. __extends(SmartArrayNoDuplicate, _super);
  8542. function SmartArrayNoDuplicate() {
  8543. var _this = _super !== null && _super.apply(this, arguments) || this;
  8544. _this._duplicateId = 0;
  8545. return _this;
  8546. }
  8547. SmartArrayNoDuplicate.prototype.push = function (value) {
  8548. _super.prototype.push.call(this, value);
  8549. if (!value.__smartArrayFlags) {
  8550. value.__smartArrayFlags = {};
  8551. }
  8552. value.__smartArrayFlags[this._id] = this._duplicateId;
  8553. };
  8554. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8555. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8556. return false;
  8557. }
  8558. this.push(value);
  8559. return true;
  8560. };
  8561. SmartArrayNoDuplicate.prototype.reset = function () {
  8562. _super.prototype.reset.call(this);
  8563. this._duplicateId++;
  8564. };
  8565. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8566. if (array.length === 0) {
  8567. return;
  8568. }
  8569. if (this.length + array.length > this.data.length) {
  8570. this.data.length = (this.length + array.length) * 2;
  8571. }
  8572. for (var index = 0; index < array.length; index++) {
  8573. var item = (array.data || array)[index];
  8574. this.pushNoDuplicate(item);
  8575. }
  8576. };
  8577. return SmartArrayNoDuplicate;
  8578. }(SmartArray));
  8579. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8580. })(BABYLON || (BABYLON = {}));
  8581. //# sourceMappingURL=babylon.smartArray.js.map
  8582. var BABYLON;
  8583. (function (BABYLON) {
  8584. /** Class used to store color gradient */
  8585. var ColorGradient = /** @class */ (function () {
  8586. function ColorGradient() {
  8587. }
  8588. /**
  8589. * Will get a color picked randomly between color1 and color2.
  8590. * If color2 is undefined then color1 will be used
  8591. * @param result defines the target Color4 to store the result in
  8592. */
  8593. ColorGradient.prototype.getColorToRef = function (result) {
  8594. if (!this.color2) {
  8595. result.copyFrom(this.color1);
  8596. return;
  8597. }
  8598. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8599. };
  8600. return ColorGradient;
  8601. }());
  8602. BABYLON.ColorGradient = ColorGradient;
  8603. /** Class used to store factor gradient */
  8604. var FactorGradient = /** @class */ (function () {
  8605. function FactorGradient() {
  8606. }
  8607. /**
  8608. * Will get a number picked randomly between factor1 and factor2.
  8609. * If factor2 is undefined then factor1 will be used
  8610. * @returns the picked number
  8611. */
  8612. FactorGradient.prototype.getFactor = function () {
  8613. if (this.factor2 === undefined) {
  8614. return this.factor1;
  8615. }
  8616. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8617. };
  8618. return FactorGradient;
  8619. }());
  8620. BABYLON.FactorGradient = FactorGradient;
  8621. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8622. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8623. var LoadFileError = /** @class */ (function (_super) {
  8624. __extends(LoadFileError, _super);
  8625. function LoadFileError(message, request) {
  8626. var _this = _super.call(this, message) || this;
  8627. _this.request = request;
  8628. _this.name = "LoadFileError";
  8629. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8630. return _this;
  8631. }
  8632. // Polyfill for Object.setPrototypeOf if necessary.
  8633. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8634. return LoadFileError;
  8635. }(Error));
  8636. BABYLON.LoadFileError = LoadFileError;
  8637. var RetryStrategy = /** @class */ (function () {
  8638. function RetryStrategy() {
  8639. }
  8640. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8641. if (maxRetries === void 0) { maxRetries = 3; }
  8642. if (baseInterval === void 0) { baseInterval = 500; }
  8643. return function (url, request, retryIndex) {
  8644. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8645. return -1;
  8646. }
  8647. return Math.pow(2, retryIndex) * baseInterval;
  8648. };
  8649. };
  8650. return RetryStrategy;
  8651. }());
  8652. BABYLON.RetryStrategy = RetryStrategy;
  8653. // Screenshots
  8654. var screenshotCanvas;
  8655. var cloneValue = function (source, destinationObject) {
  8656. if (!source)
  8657. return null;
  8658. if (source instanceof BABYLON.Mesh) {
  8659. return null;
  8660. }
  8661. if (source instanceof BABYLON.SubMesh) {
  8662. return source.clone(destinationObject);
  8663. }
  8664. else if (source.clone) {
  8665. return source.clone();
  8666. }
  8667. return null;
  8668. };
  8669. var Tools = /** @class */ (function () {
  8670. function Tools() {
  8671. }
  8672. /**
  8673. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8674. * @param u defines the coordinate on X axis
  8675. * @param v defines the coordinate on Y axis
  8676. * @param width defines the width of the source data
  8677. * @param height defines the height of the source data
  8678. * @param pixels defines the source byte array
  8679. * @param color defines the output color
  8680. */
  8681. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8682. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8683. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8684. var position = (wrappedU + wrappedV * width) * 4;
  8685. color.r = pixels[position] / 255;
  8686. color.g = pixels[position + 1] / 255;
  8687. color.b = pixels[position + 2] / 255;
  8688. color.a = pixels[position + 3] / 255;
  8689. };
  8690. /**
  8691. * Interpolates between a and b via alpha
  8692. * @param a The lower value (returned when alpha = 0)
  8693. * @param b The upper value (returned when alpha = 1)
  8694. * @param alpha The interpolation-factor
  8695. * @return The mixed value
  8696. */
  8697. Tools.Mix = function (a, b, alpha) {
  8698. return a * (1 - alpha) + b * alpha;
  8699. };
  8700. Tools.Instantiate = function (className) {
  8701. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8702. return Tools.RegisteredExternalClasses[className];
  8703. }
  8704. var arr = className.split(".");
  8705. var fn = (window || this);
  8706. for (var i = 0, len = arr.length; i < len; i++) {
  8707. fn = fn[arr[i]];
  8708. }
  8709. if (typeof fn !== "function") {
  8710. return null;
  8711. }
  8712. return fn;
  8713. };
  8714. /**
  8715. * Provides a slice function that will work even on IE
  8716. * @param data defines the array to slice
  8717. * @param start defines the start of the data (optional)
  8718. * @param end defines the end of the data (optional)
  8719. * @returns the new sliced array
  8720. */
  8721. Tools.Slice = function (data, start, end) {
  8722. if (data.slice) {
  8723. return data.slice(start, end);
  8724. }
  8725. return Array.prototype.slice.call(data, start, end);
  8726. };
  8727. Tools.SetImmediate = function (action) {
  8728. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8729. window.setImmediate(action);
  8730. }
  8731. else {
  8732. setTimeout(action, 1);
  8733. }
  8734. };
  8735. Tools.IsExponentOfTwo = function (value) {
  8736. var count = 1;
  8737. do {
  8738. count *= 2;
  8739. } while (count < value);
  8740. return count === value;
  8741. };
  8742. /**
  8743. * Returns the nearest 32-bit single precision float representation of a Number
  8744. * @param value A Number. If the parameter is of a different type, it will get converted
  8745. * to a number or to NaN if it cannot be converted
  8746. * @returns number
  8747. */
  8748. Tools.FloatRound = function (value) {
  8749. if (Math.fround) {
  8750. return Math.fround(value);
  8751. }
  8752. return (Tools._tmpFloatArray[0] = value);
  8753. };
  8754. /**
  8755. * Find the next highest power of two.
  8756. * @param x Number to start search from.
  8757. * @return Next highest power of two.
  8758. */
  8759. Tools.CeilingPOT = function (x) {
  8760. x--;
  8761. x |= x >> 1;
  8762. x |= x >> 2;
  8763. x |= x >> 4;
  8764. x |= x >> 8;
  8765. x |= x >> 16;
  8766. x++;
  8767. return x;
  8768. };
  8769. /**
  8770. * Find the next lowest power of two.
  8771. * @param x Number to start search from.
  8772. * @return Next lowest power of two.
  8773. */
  8774. Tools.FloorPOT = function (x) {
  8775. x = x | (x >> 1);
  8776. x = x | (x >> 2);
  8777. x = x | (x >> 4);
  8778. x = x | (x >> 8);
  8779. x = x | (x >> 16);
  8780. return x - (x >> 1);
  8781. };
  8782. /**
  8783. * Find the nearest power of two.
  8784. * @param x Number to start search from.
  8785. * @return Next nearest power of two.
  8786. */
  8787. Tools.NearestPOT = function (x) {
  8788. var c = Tools.CeilingPOT(x);
  8789. var f = Tools.FloorPOT(x);
  8790. return (c - x) > (x - f) ? f : c;
  8791. };
  8792. Tools.GetExponentOfTwo = function (value, max, mode) {
  8793. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8794. var pot;
  8795. switch (mode) {
  8796. case BABYLON.Engine.SCALEMODE_FLOOR:
  8797. pot = Tools.FloorPOT(value);
  8798. break;
  8799. case BABYLON.Engine.SCALEMODE_NEAREST:
  8800. pot = Tools.NearestPOT(value);
  8801. break;
  8802. case BABYLON.Engine.SCALEMODE_CEILING:
  8803. default:
  8804. pot = Tools.CeilingPOT(value);
  8805. break;
  8806. }
  8807. return Math.min(pot, max);
  8808. };
  8809. Tools.GetFilename = function (path) {
  8810. var index = path.lastIndexOf("/");
  8811. if (index < 0)
  8812. return path;
  8813. return path.substring(index + 1);
  8814. };
  8815. /**
  8816. * Extracts the "folder" part of a path (everything before the filename).
  8817. * @param uri The URI to extract the info from
  8818. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8819. * @returns The "folder" part of the path
  8820. */
  8821. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8822. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8823. var index = uri.lastIndexOf("/");
  8824. if (index < 0) {
  8825. if (returnUnchangedIfNoSlash) {
  8826. return uri;
  8827. }
  8828. return "";
  8829. }
  8830. return uri.substring(0, index + 1);
  8831. };
  8832. Tools.GetDOMTextContent = function (element) {
  8833. var result = "";
  8834. var child = element.firstChild;
  8835. while (child) {
  8836. if (child.nodeType === 3) {
  8837. result += child.textContent;
  8838. }
  8839. child = child.nextSibling;
  8840. }
  8841. return result;
  8842. };
  8843. Tools.ToDegrees = function (angle) {
  8844. return angle * 180 / Math.PI;
  8845. };
  8846. Tools.ToRadians = function (angle) {
  8847. return angle * Math.PI / 180;
  8848. };
  8849. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8850. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8851. var output = "";
  8852. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8853. var i = 0;
  8854. var bytes = new Uint8Array(buffer);
  8855. while (i < bytes.length) {
  8856. chr1 = bytes[i++];
  8857. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8858. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8859. enc1 = chr1 >> 2;
  8860. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8861. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8862. enc4 = chr3 & 63;
  8863. if (isNaN(chr2)) {
  8864. enc3 = enc4 = 64;
  8865. }
  8866. else if (isNaN(chr3)) {
  8867. enc4 = 64;
  8868. }
  8869. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8870. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8871. }
  8872. return "data:image/png;base64," + output;
  8873. };
  8874. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8875. if (bias === void 0) { bias = null; }
  8876. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8877. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8878. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8879. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8880. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8881. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8882. }
  8883. if (bias) {
  8884. minimum.x -= minimum.x * bias.x + bias.y;
  8885. minimum.y -= minimum.y * bias.x + bias.y;
  8886. minimum.z -= minimum.z * bias.x + bias.y;
  8887. maximum.x += maximum.x * bias.x + bias.y;
  8888. maximum.y += maximum.y * bias.x + bias.y;
  8889. maximum.z += maximum.z * bias.x + bias.y;
  8890. }
  8891. return {
  8892. minimum: minimum,
  8893. maximum: maximum
  8894. };
  8895. };
  8896. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8897. if (bias === void 0) { bias = null; }
  8898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8900. if (!stride) {
  8901. stride = 3;
  8902. }
  8903. for (var index = start; index < start + count; index++) {
  8904. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8907. }
  8908. if (bias) {
  8909. minimum.x -= minimum.x * bias.x + bias.y;
  8910. minimum.y -= minimum.y * bias.x + bias.y;
  8911. minimum.z -= minimum.z * bias.x + bias.y;
  8912. maximum.x += maximum.x * bias.x + bias.y;
  8913. maximum.y += maximum.y * bias.x + bias.y;
  8914. maximum.z += maximum.z * bias.x + bias.y;
  8915. }
  8916. return {
  8917. minimum: minimum,
  8918. maximum: maximum
  8919. };
  8920. };
  8921. Tools.Vector2ArrayFeeder = function (array) {
  8922. return function (index) {
  8923. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8924. var length = isFloatArray ? array.length / 2 : array.length;
  8925. if (index >= length) {
  8926. return null;
  8927. }
  8928. if (isFloatArray) {
  8929. var fa = array;
  8930. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8931. }
  8932. var a = array;
  8933. return a[index];
  8934. };
  8935. };
  8936. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8937. if (bias === void 0) { bias = null; }
  8938. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8939. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8940. var i = 0;
  8941. var cur = feeder(i++);
  8942. while (cur) {
  8943. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8944. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8945. cur = feeder(i++);
  8946. }
  8947. if (bias) {
  8948. minimum.x -= minimum.x * bias.x + bias.y;
  8949. minimum.y -= minimum.y * bias.x + bias.y;
  8950. maximum.x += maximum.x * bias.x + bias.y;
  8951. maximum.y += maximum.y * bias.x + bias.y;
  8952. }
  8953. return {
  8954. minimum: minimum,
  8955. maximum: maximum
  8956. };
  8957. };
  8958. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8959. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8960. return null;
  8961. return Array.isArray(obj) ? obj : [obj];
  8962. };
  8963. // Misc.
  8964. Tools.GetPointerPrefix = function () {
  8965. var eventPrefix = "pointer";
  8966. // Check if pointer events are supported
  8967. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8968. eventPrefix = "mouse";
  8969. }
  8970. return eventPrefix;
  8971. };
  8972. /**
  8973. * @param func - the function to be called
  8974. * @param requester - the object that will request the next frame. Falls back to window.
  8975. */
  8976. Tools.QueueNewFrame = function (func, requester) {
  8977. if (!Tools.IsWindowObjectExist()) {
  8978. return setTimeout(func, 16);
  8979. }
  8980. if (!requester) {
  8981. requester = window;
  8982. }
  8983. if (requester.requestAnimationFrame) {
  8984. return requester.requestAnimationFrame(func);
  8985. }
  8986. else if (requester.msRequestAnimationFrame) {
  8987. return requester.msRequestAnimationFrame(func);
  8988. }
  8989. else if (requester.webkitRequestAnimationFrame) {
  8990. return requester.webkitRequestAnimationFrame(func);
  8991. }
  8992. else if (requester.mozRequestAnimationFrame) {
  8993. return requester.mozRequestAnimationFrame(func);
  8994. }
  8995. else if (requester.oRequestAnimationFrame) {
  8996. return requester.oRequestAnimationFrame(func);
  8997. }
  8998. else {
  8999. return window.setTimeout(func, 16);
  9000. }
  9001. };
  9002. Tools.RequestFullscreen = function (element) {
  9003. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9004. if (!requestFunction)
  9005. return;
  9006. requestFunction.call(element);
  9007. };
  9008. Tools.ExitFullscreen = function () {
  9009. if (document.exitFullscreen) {
  9010. document.exitFullscreen();
  9011. }
  9012. else if (document.mozCancelFullScreen) {
  9013. document.mozCancelFullScreen();
  9014. }
  9015. else if (document.webkitCancelFullScreen) {
  9016. document.webkitCancelFullScreen();
  9017. }
  9018. else if (document.msCancelFullScreen) {
  9019. document.msCancelFullScreen();
  9020. }
  9021. };
  9022. Tools.SetCorsBehavior = function (url, element) {
  9023. if (url && url.indexOf("data:") === 0) {
  9024. return;
  9025. }
  9026. if (Tools.CorsBehavior) {
  9027. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9028. element.crossOrigin = Tools.CorsBehavior;
  9029. }
  9030. else {
  9031. var result = Tools.CorsBehavior(url);
  9032. if (result) {
  9033. element.crossOrigin = result;
  9034. }
  9035. }
  9036. }
  9037. };
  9038. // External files
  9039. Tools.CleanUrl = function (url) {
  9040. url = url.replace(/#/mg, "%23");
  9041. return url;
  9042. };
  9043. /**
  9044. * Loads an image as an HTMLImageElement.
  9045. * @param input url string, ArrayBuffer, or Blob to load
  9046. * @param onLoad callback called when the image successfully loads
  9047. * @param onError callback called when the image fails to load
  9048. * @param database database for caching
  9049. * @returns the HTMLImageElement of the loaded image
  9050. */
  9051. Tools.LoadImage = function (input, onLoad, onError, database) {
  9052. var url;
  9053. var usingObjectURL = false;
  9054. if (input instanceof ArrayBuffer) {
  9055. url = URL.createObjectURL(new Blob([input]));
  9056. usingObjectURL = true;
  9057. }
  9058. else if (input instanceof Blob) {
  9059. url = URL.createObjectURL(input);
  9060. usingObjectURL = true;
  9061. }
  9062. else {
  9063. url = Tools.CleanUrl(input);
  9064. url = Tools.PreprocessUrl(input);
  9065. }
  9066. var img = new Image();
  9067. Tools.SetCorsBehavior(url, img);
  9068. var loadHandler = function () {
  9069. if (usingObjectURL && img.src) {
  9070. URL.revokeObjectURL(img.src);
  9071. }
  9072. img.removeEventListener("load", loadHandler);
  9073. img.removeEventListener("error", errorHandler);
  9074. onLoad(img);
  9075. };
  9076. var errorHandler = function (err) {
  9077. if (usingObjectURL && img.src) {
  9078. URL.revokeObjectURL(img.src);
  9079. }
  9080. img.removeEventListener("load", loadHandler);
  9081. img.removeEventListener("error", errorHandler);
  9082. Tools.Error("Error while trying to load image: " + input);
  9083. if (onError) {
  9084. onError("Error while trying to load image: " + input, err);
  9085. }
  9086. };
  9087. img.addEventListener("load", loadHandler);
  9088. img.addEventListener("error", errorHandler);
  9089. var noIndexedDB = function () {
  9090. img.src = url;
  9091. };
  9092. var loadFromIndexedDB = function () {
  9093. if (database) {
  9094. database.loadImageFromDB(url, img);
  9095. }
  9096. };
  9097. //ANY database to do!
  9098. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9099. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9100. }
  9101. else {
  9102. if (url.indexOf("file:") !== -1) {
  9103. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9104. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9105. try {
  9106. var blobURL;
  9107. try {
  9108. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9109. }
  9110. catch (ex) {
  9111. // Chrome doesn't support oneTimeOnly parameter
  9112. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9113. }
  9114. img.src = blobURL;
  9115. usingObjectURL = true;
  9116. }
  9117. catch (e) {
  9118. img.src = "";
  9119. }
  9120. return img;
  9121. }
  9122. }
  9123. noIndexedDB();
  9124. }
  9125. return img;
  9126. };
  9127. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9128. url = Tools.CleanUrl(url);
  9129. url = Tools.PreprocessUrl(url);
  9130. // If file and file input are set
  9131. if (url.indexOf("file:") !== -1) {
  9132. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9133. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9134. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9135. }
  9136. }
  9137. var loadUrl = Tools.BaseUrl + url;
  9138. var aborted = false;
  9139. var fileRequest = {
  9140. onCompleteObservable: new BABYLON.Observable(),
  9141. abort: function () { return aborted = true; },
  9142. };
  9143. var requestFile = function () {
  9144. var request = new XMLHttpRequest();
  9145. var retryHandle = null;
  9146. fileRequest.abort = function () {
  9147. aborted = true;
  9148. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9149. request.abort();
  9150. }
  9151. if (retryHandle !== null) {
  9152. clearTimeout(retryHandle);
  9153. retryHandle = null;
  9154. }
  9155. };
  9156. var retryLoop = function (retryIndex) {
  9157. request.open('GET', loadUrl, true);
  9158. if (useArrayBuffer) {
  9159. request.responseType = "arraybuffer";
  9160. }
  9161. if (onProgress) {
  9162. request.addEventListener("progress", onProgress);
  9163. }
  9164. var onLoadEnd = function () {
  9165. request.removeEventListener("loadend", onLoadEnd);
  9166. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9167. fileRequest.onCompleteObservable.clear();
  9168. };
  9169. request.addEventListener("loadend", onLoadEnd);
  9170. var onReadyStateChange = function () {
  9171. if (aborted) {
  9172. return;
  9173. }
  9174. // In case of undefined state in some browsers.
  9175. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9176. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9177. request.removeEventListener("readystatechange", onReadyStateChange);
  9178. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9179. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9180. return;
  9181. }
  9182. var retryStrategy = Tools.DefaultRetryStrategy;
  9183. if (retryStrategy) {
  9184. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9185. if (waitTime !== -1) {
  9186. // Prevent the request from completing for retry.
  9187. request.removeEventListener("loadend", onLoadEnd);
  9188. request = new XMLHttpRequest();
  9189. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9190. return;
  9191. }
  9192. }
  9193. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9194. if (onError) {
  9195. onError(request, e);
  9196. }
  9197. else {
  9198. throw e;
  9199. }
  9200. }
  9201. };
  9202. request.addEventListener("readystatechange", onReadyStateChange);
  9203. request.send();
  9204. };
  9205. retryLoop(0);
  9206. };
  9207. // Caching all files
  9208. if (database && database.enableSceneOffline) {
  9209. var noIndexedDB_1 = function (request) {
  9210. if (request && request.status > 400) {
  9211. if (onError) {
  9212. onError(request);
  9213. }
  9214. }
  9215. else {
  9216. if (!aborted) {
  9217. requestFile();
  9218. }
  9219. }
  9220. };
  9221. var loadFromIndexedDB = function () {
  9222. // TODO: database needs to support aborting and should return a IFileRequest
  9223. if (aborted) {
  9224. return;
  9225. }
  9226. if (database) {
  9227. database.loadFileFromDB(url, function (data) {
  9228. if (!aborted) {
  9229. onSuccess(data);
  9230. }
  9231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9232. }, onProgress ? function (event) {
  9233. if (!aborted) {
  9234. onProgress(event);
  9235. }
  9236. } : undefined, noIndexedDB_1, useArrayBuffer);
  9237. }
  9238. };
  9239. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9240. }
  9241. else {
  9242. requestFile();
  9243. }
  9244. return fileRequest;
  9245. };
  9246. /**
  9247. * Load a script (identified by an url). When the url returns, the
  9248. * content of this file is added into a new script element, attached to the DOM (body element)
  9249. */
  9250. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9251. var head = document.getElementsByTagName('head')[0];
  9252. var script = document.createElement('script');
  9253. script.type = 'text/javascript';
  9254. script.src = scriptUrl;
  9255. script.onload = function () {
  9256. if (onSuccess) {
  9257. onSuccess();
  9258. }
  9259. };
  9260. script.onerror = function (e) {
  9261. if (onError) {
  9262. onError("Unable to load script '" + scriptUrl + "'", e);
  9263. }
  9264. };
  9265. head.appendChild(script);
  9266. };
  9267. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9268. var reader = new FileReader();
  9269. var request = {
  9270. onCompleteObservable: new BABYLON.Observable(),
  9271. abort: function () { return reader.abort(); },
  9272. };
  9273. reader.onloadend = function (e) {
  9274. request.onCompleteObservable.notifyObservers(request);
  9275. };
  9276. reader.onload = function (e) {
  9277. //target doesn't have result from ts 1.3
  9278. callback(e.target['result']);
  9279. };
  9280. reader.onprogress = progressCallback;
  9281. reader.readAsDataURL(fileToLoad);
  9282. return request;
  9283. };
  9284. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9285. var reader = new FileReader();
  9286. var request = {
  9287. onCompleteObservable: new BABYLON.Observable(),
  9288. abort: function () { return reader.abort(); },
  9289. };
  9290. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9291. reader.onerror = function (e) {
  9292. Tools.Log("Error while reading file: " + fileToLoad.name);
  9293. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9294. };
  9295. reader.onload = function (e) {
  9296. //target doesn't have result from ts 1.3
  9297. callback(e.target['result']);
  9298. };
  9299. if (progressCallBack) {
  9300. reader.onprogress = progressCallBack;
  9301. }
  9302. if (!useArrayBuffer) {
  9303. // Asynchronous read
  9304. reader.readAsText(fileToLoad);
  9305. }
  9306. else {
  9307. reader.readAsArrayBuffer(fileToLoad);
  9308. }
  9309. return request;
  9310. };
  9311. //returns a downloadable url to a file content.
  9312. Tools.FileAsURL = function (content) {
  9313. var fileBlob = new Blob([content]);
  9314. var url = window.URL || window.webkitURL;
  9315. var link = url.createObjectURL(fileBlob);
  9316. return link;
  9317. };
  9318. // Misc.
  9319. Tools.Format = function (value, decimals) {
  9320. if (decimals === void 0) { decimals = 2; }
  9321. return value.toFixed(decimals);
  9322. };
  9323. Tools.CheckExtends = function (v, min, max) {
  9324. if (v.x < min.x)
  9325. min.x = v.x;
  9326. if (v.y < min.y)
  9327. min.y = v.y;
  9328. if (v.z < min.z)
  9329. min.z = v.z;
  9330. if (v.x > max.x)
  9331. max.x = v.x;
  9332. if (v.y > max.y)
  9333. max.y = v.y;
  9334. if (v.z > max.z)
  9335. max.z = v.z;
  9336. };
  9337. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9338. for (var prop in source) {
  9339. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9340. continue;
  9341. }
  9342. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9343. continue;
  9344. }
  9345. var sourceValue = source[prop];
  9346. var typeOfSourceValue = typeof sourceValue;
  9347. if (typeOfSourceValue === "function") {
  9348. continue;
  9349. }
  9350. try {
  9351. if (typeOfSourceValue === "object") {
  9352. if (sourceValue instanceof Array) {
  9353. destination[prop] = [];
  9354. if (sourceValue.length > 0) {
  9355. if (typeof sourceValue[0] == "object") {
  9356. for (var index = 0; index < sourceValue.length; index++) {
  9357. var clonedValue = cloneValue(sourceValue[index], destination);
  9358. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9359. destination[prop].push(clonedValue);
  9360. }
  9361. }
  9362. }
  9363. else {
  9364. destination[prop] = sourceValue.slice(0);
  9365. }
  9366. }
  9367. }
  9368. else {
  9369. destination[prop] = cloneValue(sourceValue, destination);
  9370. }
  9371. }
  9372. else {
  9373. destination[prop] = sourceValue;
  9374. }
  9375. }
  9376. catch (e) {
  9377. // Just ignore error (it could be because of a read-only property)
  9378. }
  9379. }
  9380. };
  9381. Tools.IsEmpty = function (obj) {
  9382. for (var i in obj) {
  9383. if (obj.hasOwnProperty(i)) {
  9384. return false;
  9385. }
  9386. }
  9387. return true;
  9388. };
  9389. Tools.RegisterTopRootEvents = function (events) {
  9390. for (var index = 0; index < events.length; index++) {
  9391. var event = events[index];
  9392. window.addEventListener(event.name, event.handler, false);
  9393. try {
  9394. if (window.parent) {
  9395. window.parent.addEventListener(event.name, event.handler, false);
  9396. }
  9397. }
  9398. catch (e) {
  9399. // Silently fails...
  9400. }
  9401. }
  9402. };
  9403. Tools.UnregisterTopRootEvents = function (events) {
  9404. for (var index = 0; index < events.length; index++) {
  9405. var event = events[index];
  9406. window.removeEventListener(event.name, event.handler);
  9407. try {
  9408. if (window.parent) {
  9409. window.parent.removeEventListener(event.name, event.handler);
  9410. }
  9411. }
  9412. catch (e) {
  9413. // Silently fails...
  9414. }
  9415. }
  9416. };
  9417. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9418. if (mimeType === void 0) { mimeType = "image/png"; }
  9419. // Read the contents of the framebuffer
  9420. var numberOfChannelsByLine = width * 4;
  9421. var halfHeight = height / 2;
  9422. //Reading datas from WebGL
  9423. var data = engine.readPixels(0, 0, width, height);
  9424. //To flip image on Y axis.
  9425. for (var i = 0; i < halfHeight; i++) {
  9426. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9427. var currentCell = j + i * numberOfChannelsByLine;
  9428. var targetLine = height - i - 1;
  9429. var targetCell = j + targetLine * numberOfChannelsByLine;
  9430. var temp = data[currentCell];
  9431. data[currentCell] = data[targetCell];
  9432. data[targetCell] = temp;
  9433. }
  9434. }
  9435. // Create a 2D canvas to store the result
  9436. if (!screenshotCanvas) {
  9437. screenshotCanvas = document.createElement('canvas');
  9438. }
  9439. screenshotCanvas.width = width;
  9440. screenshotCanvas.height = height;
  9441. var context = screenshotCanvas.getContext('2d');
  9442. if (context) {
  9443. // Copy the pixels to a 2D canvas
  9444. var imageData = context.createImageData(width, height);
  9445. var castData = (imageData.data);
  9446. castData.set(data);
  9447. context.putImageData(imageData, 0, 0);
  9448. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9449. }
  9450. };
  9451. /**
  9452. * Converts the canvas data to blob.
  9453. * This acts as a polyfill for browsers not supporting the to blob function.
  9454. * @param canvas Defines the canvas to extract the data from
  9455. * @param successCallback Defines the callback triggered once the data are available
  9456. * @param mimeType Defines the mime type of the result
  9457. */
  9458. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9459. if (mimeType === void 0) { mimeType = "image/png"; }
  9460. // We need HTMLCanvasElement.toBlob for HD screenshots
  9461. if (!canvas.toBlob) {
  9462. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9463. canvas.toBlob = function (callback, type, quality) {
  9464. var _this = this;
  9465. setTimeout(function () {
  9466. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9467. for (var i = 0; i < len; i++) {
  9468. arr[i] = binStr.charCodeAt(i);
  9469. }
  9470. callback(new Blob([arr]));
  9471. });
  9472. };
  9473. }
  9474. canvas.toBlob(function (blob) {
  9475. successCallback(blob);
  9476. }, mimeType);
  9477. };
  9478. /**
  9479. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9480. * @param successCallback Defines the callback triggered once the data are available
  9481. * @param mimeType Defines the mime type of the result
  9482. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9483. */
  9484. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9485. if (mimeType === void 0) { mimeType = "image/png"; }
  9486. if (successCallback) {
  9487. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9488. successCallback(base64Image);
  9489. }
  9490. else {
  9491. this.ToBlob(screenshotCanvas, function (blob) {
  9492. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9493. if (("download" in document.createElement("a"))) {
  9494. if (!fileName) {
  9495. var date = new Date();
  9496. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9497. fileName = "screenshot_" + stringDate + ".png";
  9498. }
  9499. Tools.Download(blob, fileName);
  9500. }
  9501. else {
  9502. var url = URL.createObjectURL(blob);
  9503. var newWindow = window.open("");
  9504. if (!newWindow)
  9505. return;
  9506. var img = newWindow.document.createElement("img");
  9507. img.onload = function () {
  9508. // no longer need to read the blob so it's revoked
  9509. URL.revokeObjectURL(url);
  9510. };
  9511. img.src = url;
  9512. newWindow.document.body.appendChild(img);
  9513. }
  9514. }, mimeType);
  9515. }
  9516. };
  9517. /**
  9518. * Downloads a blob in the browser
  9519. * @param blob defines the blob to download
  9520. * @param fileName defines the name of the downloaded file
  9521. */
  9522. Tools.Download = function (blob, fileName) {
  9523. if (navigator && navigator.msSaveBlob) {
  9524. navigator.msSaveBlob(blob, fileName);
  9525. return;
  9526. }
  9527. var url = window.URL.createObjectURL(blob);
  9528. var a = document.createElement("a");
  9529. document.body.appendChild(a);
  9530. a.style.display = "none";
  9531. a.href = url;
  9532. a.download = fileName;
  9533. a.addEventListener("click", function () {
  9534. if (a.parentElement) {
  9535. a.parentElement.removeChild(a);
  9536. }
  9537. });
  9538. a.click();
  9539. window.URL.revokeObjectURL(url);
  9540. };
  9541. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9542. if (mimeType === void 0) { mimeType = "image/png"; }
  9543. var width;
  9544. var height;
  9545. // If a precision value is specified
  9546. if (size.precision) {
  9547. width = Math.round(engine.getRenderWidth() * size.precision);
  9548. height = Math.round(width / engine.getAspectRatio(camera));
  9549. }
  9550. else if (size.width && size.height) {
  9551. width = size.width;
  9552. height = size.height;
  9553. }
  9554. //If passing only width, computing height to keep display canvas ratio.
  9555. else if (size.width && !size.height) {
  9556. width = size.width;
  9557. height = Math.round(width / engine.getAspectRatio(camera));
  9558. }
  9559. //If passing only height, computing width to keep display canvas ratio.
  9560. else if (size.height && !size.width) {
  9561. height = size.height;
  9562. width = Math.round(height * engine.getAspectRatio(camera));
  9563. }
  9564. //Assuming here that "size" parameter is a number
  9565. else if (!isNaN(size)) {
  9566. height = size;
  9567. width = size;
  9568. }
  9569. else {
  9570. Tools.Error("Invalid 'size' parameter !");
  9571. return;
  9572. }
  9573. if (!screenshotCanvas) {
  9574. screenshotCanvas = document.createElement('canvas');
  9575. }
  9576. screenshotCanvas.width = width;
  9577. screenshotCanvas.height = height;
  9578. var renderContext = screenshotCanvas.getContext("2d");
  9579. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9580. var newWidth = width;
  9581. var newHeight = newWidth / ratio;
  9582. if (newHeight > height) {
  9583. newHeight = height;
  9584. newWidth = newHeight * ratio;
  9585. }
  9586. var offsetX = Math.max(0, width - newWidth) / 2;
  9587. var offsetY = Math.max(0, height - newHeight) / 2;
  9588. var renderingCanvas = engine.getRenderingCanvas();
  9589. if (renderContext && renderingCanvas) {
  9590. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9591. }
  9592. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9593. };
  9594. /**
  9595. * Generates an image screenshot from the specified camera.
  9596. *
  9597. * @param engine The engine to use for rendering
  9598. * @param camera The camera to use for rendering
  9599. * @param size This parameter can be set to a single number or to an object with the
  9600. * following (optional) properties: precision, width, height. If a single number is passed,
  9601. * it will be used for both width and height. If an object is passed, the screenshot size
  9602. * will be derived from the parameters. The precision property is a multiplier allowing
  9603. * rendering at a higher or lower resolution.
  9604. * @param successCallback The callback receives a single parameter which contains the
  9605. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9606. * src parameter of an <img> to display it.
  9607. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9608. * Check your browser for supported MIME types.
  9609. * @param samples Texture samples (default: 1)
  9610. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9611. * @param fileName A name for for the downloaded file.
  9612. * @constructor
  9613. */
  9614. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9615. if (mimeType === void 0) { mimeType = "image/png"; }
  9616. if (samples === void 0) { samples = 1; }
  9617. if (antialiasing === void 0) { antialiasing = false; }
  9618. var width;
  9619. var height;
  9620. //If a precision value is specified
  9621. if (size.precision) {
  9622. width = Math.round(engine.getRenderWidth() * size.precision);
  9623. height = Math.round(width / engine.getAspectRatio(camera));
  9624. size = { width: width, height: height };
  9625. }
  9626. else if (size.width && size.height) {
  9627. width = size.width;
  9628. height = size.height;
  9629. }
  9630. //If passing only width, computing height to keep display canvas ratio.
  9631. else if (size.width && !size.height) {
  9632. width = size.width;
  9633. height = Math.round(width / engine.getAspectRatio(camera));
  9634. size = { width: width, height: height };
  9635. }
  9636. //If passing only height, computing width to keep display canvas ratio.
  9637. else if (size.height && !size.width) {
  9638. height = size.height;
  9639. width = Math.round(height * engine.getAspectRatio(camera));
  9640. size = { width: width, height: height };
  9641. }
  9642. //Assuming here that "size" parameter is a number
  9643. else if (!isNaN(size)) {
  9644. height = size;
  9645. width = size;
  9646. }
  9647. else {
  9648. Tools.Error("Invalid 'size' parameter !");
  9649. return;
  9650. }
  9651. var scene = camera.getScene();
  9652. var previousCamera = null;
  9653. if (scene.activeCamera !== camera) {
  9654. previousCamera = scene.activeCamera;
  9655. scene.activeCamera = camera;
  9656. }
  9657. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9658. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9659. texture.renderList = null;
  9660. texture.samples = samples;
  9661. if (antialiasing) {
  9662. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9663. }
  9664. texture.onAfterRenderObservable.add(function () {
  9665. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9666. });
  9667. scene.incrementRenderId();
  9668. scene.resetCachedMaterial();
  9669. texture.render(true);
  9670. texture.dispose();
  9671. if (previousCamera) {
  9672. scene.activeCamera = previousCamera;
  9673. }
  9674. camera.getProjectionMatrix(true); // Force cache refresh;
  9675. };
  9676. // XHR response validator for local file scenario
  9677. Tools.ValidateXHRData = function (xhr, dataType) {
  9678. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9679. if (dataType === void 0) { dataType = 7; }
  9680. try {
  9681. if (dataType & 1) {
  9682. if (xhr.responseText && xhr.responseText.length > 0) {
  9683. return true;
  9684. }
  9685. else if (dataType === 1) {
  9686. return false;
  9687. }
  9688. }
  9689. if (dataType & 2) {
  9690. // Check header width and height since there is no "TGA" magic number
  9691. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9692. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9693. return true;
  9694. }
  9695. else if (dataType === 2) {
  9696. return false;
  9697. }
  9698. }
  9699. if (dataType & 4) {
  9700. // Check for the "DDS" magic number
  9701. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9702. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9703. return true;
  9704. }
  9705. else {
  9706. return false;
  9707. }
  9708. }
  9709. }
  9710. catch (e) {
  9711. // Global protection
  9712. }
  9713. return false;
  9714. };
  9715. /**
  9716. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9717. * Be aware Math.random() could cause collisions, but:
  9718. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9719. */
  9720. Tools.RandomId = function () {
  9721. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9722. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9723. return v.toString(16);
  9724. });
  9725. };
  9726. /**
  9727. * Test if the given uri is a base64 string.
  9728. * @param uri The uri to test
  9729. * @return True if the uri is a base64 string or false otherwise.
  9730. */
  9731. Tools.IsBase64 = function (uri) {
  9732. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9733. };
  9734. /**
  9735. * Decode the given base64 uri.
  9736. * @param uri The uri to decode
  9737. * @return The decoded base64 data.
  9738. */
  9739. Tools.DecodeBase64 = function (uri) {
  9740. var decodedString = atob(uri.split(",")[1]);
  9741. var bufferLength = decodedString.length;
  9742. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9743. for (var i = 0; i < bufferLength; i++) {
  9744. bufferView[i] = decodedString.charCodeAt(i);
  9745. }
  9746. return bufferView.buffer;
  9747. };
  9748. Object.defineProperty(Tools, "NoneLogLevel", {
  9749. get: function () {
  9750. return Tools._NoneLogLevel;
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. Object.defineProperty(Tools, "MessageLogLevel", {
  9756. get: function () {
  9757. return Tools._MessageLogLevel;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. Object.defineProperty(Tools, "WarningLogLevel", {
  9763. get: function () {
  9764. return Tools._WarningLogLevel;
  9765. },
  9766. enumerable: true,
  9767. configurable: true
  9768. });
  9769. Object.defineProperty(Tools, "ErrorLogLevel", {
  9770. get: function () {
  9771. return Tools._ErrorLogLevel;
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(Tools, "AllLogLevel", {
  9777. get: function () {
  9778. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9779. },
  9780. enumerable: true,
  9781. configurable: true
  9782. });
  9783. Tools._AddLogEntry = function (entry) {
  9784. Tools._LogCache = entry + Tools._LogCache;
  9785. if (Tools.OnNewCacheEntry) {
  9786. Tools.OnNewCacheEntry(entry);
  9787. }
  9788. };
  9789. Tools._FormatMessage = function (message) {
  9790. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9791. var date = new Date();
  9792. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9793. };
  9794. Tools._LogDisabled = function (message) {
  9795. // nothing to do
  9796. };
  9797. Tools._LogEnabled = function (message) {
  9798. var formattedMessage = Tools._FormatMessage(message);
  9799. console.log("BJS - " + formattedMessage);
  9800. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9801. Tools._AddLogEntry(entry);
  9802. };
  9803. Tools._WarnDisabled = function (message) {
  9804. // nothing to do
  9805. };
  9806. Tools._WarnEnabled = function (message) {
  9807. var formattedMessage = Tools._FormatMessage(message);
  9808. console.warn("BJS - " + formattedMessage);
  9809. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9810. Tools._AddLogEntry(entry);
  9811. };
  9812. Tools._ErrorDisabled = function (message) {
  9813. // nothing to do
  9814. };
  9815. Tools._ErrorEnabled = function (message) {
  9816. Tools.errorsCount++;
  9817. var formattedMessage = Tools._FormatMessage(message);
  9818. console.error("BJS - " + formattedMessage);
  9819. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9820. Tools._AddLogEntry(entry);
  9821. };
  9822. Object.defineProperty(Tools, "LogCache", {
  9823. get: function () {
  9824. return Tools._LogCache;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Tools.ClearLogCache = function () {
  9830. Tools._LogCache = "";
  9831. Tools.errorsCount = 0;
  9832. };
  9833. Object.defineProperty(Tools, "LogLevels", {
  9834. set: function (level) {
  9835. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9836. Tools.Log = Tools._LogEnabled;
  9837. }
  9838. else {
  9839. Tools.Log = Tools._LogDisabled;
  9840. }
  9841. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9842. Tools.Warn = Tools._WarnEnabled;
  9843. }
  9844. else {
  9845. Tools.Warn = Tools._WarnDisabled;
  9846. }
  9847. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9848. Tools.Error = Tools._ErrorEnabled;
  9849. }
  9850. else {
  9851. Tools.Error = Tools._ErrorDisabled;
  9852. }
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. /**
  9858. * Check if the loaded document was accessed via `file:`-Protocol.
  9859. * @returns boolean
  9860. */
  9861. Tools.IsFileURL = function () {
  9862. return location.protocol === "file:";
  9863. };
  9864. Tools.IsWindowObjectExist = function () {
  9865. return (typeof window) !== "undefined";
  9866. };
  9867. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9868. get: function () {
  9869. return Tools._PerformanceNoneLogLevel;
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9875. get: function () {
  9876. return Tools._PerformanceUserMarkLogLevel;
  9877. },
  9878. enumerable: true,
  9879. configurable: true
  9880. });
  9881. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9882. get: function () {
  9883. return Tools._PerformanceConsoleLogLevel;
  9884. },
  9885. enumerable: true,
  9886. configurable: true
  9887. });
  9888. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9889. set: function (level) {
  9890. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9891. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9892. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9893. return;
  9894. }
  9895. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9896. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9897. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9898. return;
  9899. }
  9900. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9901. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9907. };
  9908. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9909. };
  9910. Tools._StartUserMark = function (counterName, condition) {
  9911. if (condition === void 0) { condition = true; }
  9912. if (!Tools._performance) {
  9913. if (!Tools.IsWindowObjectExist()) {
  9914. return;
  9915. }
  9916. Tools._performance = window.performance;
  9917. }
  9918. if (!condition || !Tools._performance.mark) {
  9919. return;
  9920. }
  9921. Tools._performance.mark(counterName + "-Begin");
  9922. };
  9923. Tools._EndUserMark = function (counterName, condition) {
  9924. if (condition === void 0) { condition = true; }
  9925. if (!condition || !Tools._performance.mark) {
  9926. return;
  9927. }
  9928. Tools._performance.mark(counterName + "-End");
  9929. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9930. };
  9931. Tools._StartPerformanceConsole = function (counterName, condition) {
  9932. if (condition === void 0) { condition = true; }
  9933. if (!condition) {
  9934. return;
  9935. }
  9936. Tools._StartUserMark(counterName, condition);
  9937. if (console.time) {
  9938. console.time(counterName);
  9939. }
  9940. };
  9941. Tools._EndPerformanceConsole = function (counterName, condition) {
  9942. if (condition === void 0) { condition = true; }
  9943. if (!condition) {
  9944. return;
  9945. }
  9946. Tools._EndUserMark(counterName, condition);
  9947. if (console.time) {
  9948. console.timeEnd(counterName);
  9949. }
  9950. };
  9951. Object.defineProperty(Tools, "Now", {
  9952. get: function () {
  9953. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9954. return window.performance.now();
  9955. }
  9956. return Date.now();
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. /**
  9962. * This method will return the name of the class used to create the instance of the given object.
  9963. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9964. * @param object the object to get the class name from
  9965. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9966. */
  9967. Tools.GetClassName = function (object, isType) {
  9968. if (isType === void 0) { isType = false; }
  9969. var name = null;
  9970. if (!isType && object.getClassName) {
  9971. name = object.getClassName();
  9972. }
  9973. else {
  9974. if (object instanceof Object) {
  9975. var classObj = isType ? object : Object.getPrototypeOf(object);
  9976. name = classObj.constructor["__bjsclassName__"];
  9977. }
  9978. if (!name) {
  9979. name = typeof object;
  9980. }
  9981. }
  9982. return name;
  9983. };
  9984. Tools.First = function (array, predicate) {
  9985. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9986. var el = array_1[_i];
  9987. if (predicate(el)) {
  9988. return el;
  9989. }
  9990. }
  9991. return null;
  9992. };
  9993. /**
  9994. * This method will return the name of the full name of the class, including its owning module (if any).
  9995. * 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).
  9996. * @param object the object to get the class name from
  9997. * @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.
  9998. */
  9999. Tools.getFullClassName = function (object, isType) {
  10000. if (isType === void 0) { isType = false; }
  10001. var className = null;
  10002. var moduleName = null;
  10003. if (!isType && object.getClassName) {
  10004. className = object.getClassName();
  10005. }
  10006. else {
  10007. if (object instanceof Object) {
  10008. var classObj = isType ? object : Object.getPrototypeOf(object);
  10009. className = classObj.constructor["__bjsclassName__"];
  10010. moduleName = classObj.constructor["__bjsmoduleName__"];
  10011. }
  10012. if (!className) {
  10013. className = typeof object;
  10014. }
  10015. }
  10016. if (!className) {
  10017. return null;
  10018. }
  10019. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10020. };
  10021. /**
  10022. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  10023. * @param array
  10024. */
  10025. Tools.arrayOrStringFeeder = function (array) {
  10026. return function (index) {
  10027. if (index >= array.length) {
  10028. return null;
  10029. }
  10030. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10031. if (val && val.getHashCode) {
  10032. val = val.getHashCode();
  10033. }
  10034. if (typeof val === "string") {
  10035. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10036. }
  10037. return val;
  10038. };
  10039. };
  10040. /**
  10041. * Compute the hashCode of a stream of number
  10042. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10043. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10044. * @return the hash code computed
  10045. */
  10046. Tools.hashCodeFromStream = function (feeder) {
  10047. // Based from here: http://stackoverflow.com/a/7616484/802124
  10048. var hash = 0;
  10049. var index = 0;
  10050. var chr = feeder(index++);
  10051. while (chr != null) {
  10052. hash = ((hash << 5) - hash) + chr;
  10053. hash |= 0; // Convert to 32bit integer
  10054. chr = feeder(index++);
  10055. }
  10056. return hash;
  10057. };
  10058. /**
  10059. * Returns a promise that resolves after the given amount of time.
  10060. * @param delay Number of milliseconds to delay
  10061. * @returns Promise that resolves after the given amount of time
  10062. */
  10063. Tools.DelayAsync = function (delay) {
  10064. return new Promise(function (resolve) {
  10065. setTimeout(function () {
  10066. resolve();
  10067. }, delay);
  10068. });
  10069. };
  10070. /**
  10071. * Gets the current gradient from an array of IValueGradient
  10072. * @param ratio defines the current ratio to get
  10073. * @param gradients defines the array of IValueGradient
  10074. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10075. */
  10076. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10077. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10078. var currentGradient = gradients[gradientIndex];
  10079. var nextGradient = gradients[gradientIndex + 1];
  10080. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10081. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10082. updateFunc(currentGradient, nextGradient, scale);
  10083. }
  10084. }
  10085. };
  10086. Tools.BaseUrl = "";
  10087. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10088. /**
  10089. * Default behaviour for cors in the application.
  10090. * It can be a string if the expected behavior is identical in the entire app.
  10091. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10092. */
  10093. Tools.CorsBehavior = "anonymous";
  10094. Tools.UseFallbackTexture = true;
  10095. /**
  10096. * Use this object to register external classes like custom textures or material
  10097. * to allow the laoders to instantiate them
  10098. */
  10099. Tools.RegisteredExternalClasses = {};
  10100. // Used in case of a texture loading problem
  10101. 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";
  10102. Tools._tmpFloatArray = new Float32Array(1);
  10103. Tools.PreprocessUrl = function (url) {
  10104. return url;
  10105. };
  10106. // Logs
  10107. Tools._NoneLogLevel = 0;
  10108. Tools._MessageLogLevel = 1;
  10109. Tools._WarningLogLevel = 2;
  10110. Tools._ErrorLogLevel = 4;
  10111. Tools._LogCache = "";
  10112. Tools.errorsCount = 0;
  10113. Tools.Log = Tools._LogEnabled;
  10114. Tools.Warn = Tools._WarnEnabled;
  10115. Tools.Error = Tools._ErrorEnabled;
  10116. // Performances
  10117. Tools._PerformanceNoneLogLevel = 0;
  10118. Tools._PerformanceUserMarkLogLevel = 1;
  10119. Tools._PerformanceConsoleLogLevel = 2;
  10120. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10121. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10122. return Tools;
  10123. }());
  10124. BABYLON.Tools = Tools;
  10125. /**
  10126. * This class is used to track a performance counter which is number based.
  10127. * The user has access to many properties which give statistics of different nature
  10128. *
  10129. * The implementer can track two kinds of Performance Counter: time and count
  10130. * 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.
  10131. * 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.
  10132. */
  10133. var PerfCounter = /** @class */ (function () {
  10134. function PerfCounter() {
  10135. this._startMonitoringTime = 0;
  10136. this._min = 0;
  10137. this._max = 0;
  10138. this._average = 0;
  10139. this._lastSecAverage = 0;
  10140. this._current = 0;
  10141. this._totalValueCount = 0;
  10142. this._totalAccumulated = 0;
  10143. this._lastSecAccumulated = 0;
  10144. this._lastSecTime = 0;
  10145. this._lastSecValueCount = 0;
  10146. }
  10147. Object.defineProperty(PerfCounter.prototype, "min", {
  10148. /**
  10149. * Returns the smallest value ever
  10150. */
  10151. get: function () {
  10152. return this._min;
  10153. },
  10154. enumerable: true,
  10155. configurable: true
  10156. });
  10157. Object.defineProperty(PerfCounter.prototype, "max", {
  10158. /**
  10159. * Returns the biggest value ever
  10160. */
  10161. get: function () {
  10162. return this._max;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(PerfCounter.prototype, "average", {
  10168. /**
  10169. * Returns the average value since the performance counter is running
  10170. */
  10171. get: function () {
  10172. return this._average;
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10178. /**
  10179. * Returns the average value of the last second the counter was monitored
  10180. */
  10181. get: function () {
  10182. return this._lastSecAverage;
  10183. },
  10184. enumerable: true,
  10185. configurable: true
  10186. });
  10187. Object.defineProperty(PerfCounter.prototype, "current", {
  10188. /**
  10189. * Returns the current value
  10190. */
  10191. get: function () {
  10192. return this._current;
  10193. },
  10194. enumerable: true,
  10195. configurable: true
  10196. });
  10197. Object.defineProperty(PerfCounter.prototype, "total", {
  10198. get: function () {
  10199. return this._totalAccumulated;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. Object.defineProperty(PerfCounter.prototype, "count", {
  10205. get: function () {
  10206. return this._totalValueCount;
  10207. },
  10208. enumerable: true,
  10209. configurable: true
  10210. });
  10211. /**
  10212. * Call this method to start monitoring a new frame.
  10213. * 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.
  10214. */
  10215. PerfCounter.prototype.fetchNewFrame = function () {
  10216. this._totalValueCount++;
  10217. this._current = 0;
  10218. this._lastSecValueCount++;
  10219. };
  10220. /**
  10221. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10222. * @param newCount the count value to add to the monitored count
  10223. * @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.
  10224. */
  10225. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10226. if (!PerfCounter.Enabled) {
  10227. return;
  10228. }
  10229. this._current += newCount;
  10230. if (fetchResult) {
  10231. this._fetchResult();
  10232. }
  10233. };
  10234. /**
  10235. * Start monitoring this performance counter
  10236. */
  10237. PerfCounter.prototype.beginMonitoring = function () {
  10238. if (!PerfCounter.Enabled) {
  10239. return;
  10240. }
  10241. this._startMonitoringTime = Tools.Now;
  10242. };
  10243. /**
  10244. * Compute the time lapsed since the previous beginMonitoring() call.
  10245. * @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
  10246. */
  10247. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10248. if (newFrame === void 0) { newFrame = true; }
  10249. if (!PerfCounter.Enabled) {
  10250. return;
  10251. }
  10252. if (newFrame) {
  10253. this.fetchNewFrame();
  10254. }
  10255. var currentTime = Tools.Now;
  10256. this._current = currentTime - this._startMonitoringTime;
  10257. if (newFrame) {
  10258. this._fetchResult();
  10259. }
  10260. };
  10261. PerfCounter.prototype._fetchResult = function () {
  10262. this._totalAccumulated += this._current;
  10263. this._lastSecAccumulated += this._current;
  10264. // Min/Max update
  10265. this._min = Math.min(this._min, this._current);
  10266. this._max = Math.max(this._max, this._current);
  10267. this._average = this._totalAccumulated / this._totalValueCount;
  10268. // Reset last sec?
  10269. var now = Tools.Now;
  10270. if ((now - this._lastSecTime) > 1000) {
  10271. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10272. this._lastSecTime = now;
  10273. this._lastSecAccumulated = 0;
  10274. this._lastSecValueCount = 0;
  10275. }
  10276. };
  10277. PerfCounter.Enabled = true;
  10278. return PerfCounter;
  10279. }());
  10280. BABYLON.PerfCounter = PerfCounter;
  10281. /**
  10282. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10283. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10284. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10285. * @param name The name of the class, case should be preserved
  10286. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10287. */
  10288. function className(name, module) {
  10289. return function (target) {
  10290. target["__bjsclassName__"] = name;
  10291. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10292. };
  10293. }
  10294. BABYLON.className = className;
  10295. /**
  10296. * An implementation of a loop for asynchronous functions.
  10297. */
  10298. var AsyncLoop = /** @class */ (function () {
  10299. /**
  10300. * Constroctor.
  10301. * @param iterations the number of iterations.
  10302. * @param _fn the function to run each iteration
  10303. * @param _successCallback the callback that will be called upon succesful execution
  10304. * @param offset starting offset.
  10305. */
  10306. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10307. if (offset === void 0) { offset = 0; }
  10308. this.iterations = iterations;
  10309. this._fn = _fn;
  10310. this._successCallback = _successCallback;
  10311. this.index = offset - 1;
  10312. this._done = false;
  10313. }
  10314. /**
  10315. * Execute the next iteration. Must be called after the last iteration was finished.
  10316. */
  10317. AsyncLoop.prototype.executeNext = function () {
  10318. if (!this._done) {
  10319. if (this.index + 1 < this.iterations) {
  10320. ++this.index;
  10321. this._fn(this);
  10322. }
  10323. else {
  10324. this.breakLoop();
  10325. }
  10326. }
  10327. };
  10328. /**
  10329. * Break the loop and run the success callback.
  10330. */
  10331. AsyncLoop.prototype.breakLoop = function () {
  10332. this._done = true;
  10333. this._successCallback();
  10334. };
  10335. /**
  10336. * Helper function
  10337. */
  10338. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10339. if (offset === void 0) { offset = 0; }
  10340. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10341. loop.executeNext();
  10342. return loop;
  10343. };
  10344. /**
  10345. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10346. * @param iterations total number of iterations
  10347. * @param syncedIterations number of synchronous iterations in each async iteration.
  10348. * @param fn the function to call each iteration.
  10349. * @param callback a success call back that will be called when iterating stops.
  10350. * @param breakFunction a break condition (optional)
  10351. * @param timeout timeout settings for the setTimeout function. default - 0.
  10352. * @constructor
  10353. */
  10354. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10355. if (timeout === void 0) { timeout = 0; }
  10356. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10357. if (breakFunction && breakFunction())
  10358. loop.breakLoop();
  10359. else {
  10360. setTimeout(function () {
  10361. for (var i = 0; i < syncedIterations; ++i) {
  10362. var iteration = (loop.index * syncedIterations) + i;
  10363. if (iteration >= iterations)
  10364. break;
  10365. fn(iteration);
  10366. if (breakFunction && breakFunction()) {
  10367. loop.breakLoop();
  10368. break;
  10369. }
  10370. }
  10371. loop.executeNext();
  10372. }, timeout);
  10373. }
  10374. }, callback);
  10375. };
  10376. return AsyncLoop;
  10377. }());
  10378. BABYLON.AsyncLoop = AsyncLoop;
  10379. })(BABYLON || (BABYLON = {}));
  10380. //# sourceMappingURL=babylon.tools.js.map
  10381. var BABYLON;
  10382. (function (BABYLON) {
  10383. var PromiseStates;
  10384. (function (PromiseStates) {
  10385. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10386. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10387. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10388. })(PromiseStates || (PromiseStates = {}));
  10389. var FulFillmentAgregator = /** @class */ (function () {
  10390. function FulFillmentAgregator() {
  10391. this.count = 0;
  10392. this.target = 0;
  10393. this.results = [];
  10394. }
  10395. return FulFillmentAgregator;
  10396. }());
  10397. var InternalPromise = /** @class */ (function () {
  10398. function InternalPromise(resolver) {
  10399. var _this = this;
  10400. this._state = PromiseStates.Pending;
  10401. this._children = new Array();
  10402. this._rejectWasConsumed = false;
  10403. if (!resolver) {
  10404. return;
  10405. }
  10406. try {
  10407. resolver(function (value) {
  10408. _this._resolve(value);
  10409. }, function (reason) {
  10410. _this._reject(reason);
  10411. });
  10412. }
  10413. catch (e) {
  10414. this._reject(e);
  10415. }
  10416. }
  10417. Object.defineProperty(InternalPromise.prototype, "_result", {
  10418. get: function () {
  10419. return this._resultValue;
  10420. },
  10421. set: function (value) {
  10422. this._resultValue = value;
  10423. if (this._parent && this._parent._result === undefined) {
  10424. this._parent._result = value;
  10425. }
  10426. },
  10427. enumerable: true,
  10428. configurable: true
  10429. });
  10430. InternalPromise.prototype.catch = function (onRejected) {
  10431. return this.then(undefined, onRejected);
  10432. };
  10433. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10434. var _this = this;
  10435. var newPromise = new InternalPromise();
  10436. newPromise._onFulfilled = onFulfilled;
  10437. newPromise._onRejected = onRejected;
  10438. // Composition
  10439. this._children.push(newPromise);
  10440. newPromise._parent = this;
  10441. if (this._state !== PromiseStates.Pending) {
  10442. BABYLON.Tools.SetImmediate(function () {
  10443. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10444. var returnedValue = newPromise._resolve(_this._result);
  10445. if (returnedValue !== undefined && returnedValue !== null) {
  10446. if (returnedValue._state !== undefined) {
  10447. var returnedPromise = returnedValue;
  10448. newPromise._children.push(returnedPromise);
  10449. returnedPromise._parent = newPromise;
  10450. newPromise = returnedPromise;
  10451. }
  10452. else {
  10453. newPromise._result = returnedValue;
  10454. }
  10455. }
  10456. }
  10457. else {
  10458. newPromise._reject(_this._reason);
  10459. }
  10460. });
  10461. }
  10462. return newPromise;
  10463. };
  10464. InternalPromise.prototype._moveChildren = function (children) {
  10465. var _this = this;
  10466. var _a;
  10467. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10468. this._children.forEach(function (child) {
  10469. child._parent = _this;
  10470. });
  10471. if (this._state === PromiseStates.Fulfilled) {
  10472. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10473. var child = _b[_i];
  10474. child._resolve(this._result);
  10475. }
  10476. }
  10477. else if (this._state === PromiseStates.Rejected) {
  10478. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10479. var child = _d[_c];
  10480. child._reject(this._reason);
  10481. }
  10482. }
  10483. };
  10484. InternalPromise.prototype._resolve = function (value) {
  10485. try {
  10486. this._state = PromiseStates.Fulfilled;
  10487. var returnedValue = null;
  10488. if (this._onFulfilled) {
  10489. returnedValue = this._onFulfilled(value);
  10490. }
  10491. if (returnedValue !== undefined && returnedValue !== null) {
  10492. if (returnedValue._state !== undefined) {
  10493. // Transmit children
  10494. var returnedPromise = returnedValue;
  10495. returnedPromise._parent = this;
  10496. returnedPromise._moveChildren(this._children);
  10497. value = returnedPromise._result;
  10498. }
  10499. else {
  10500. value = returnedValue;
  10501. }
  10502. }
  10503. this._result = value;
  10504. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10505. var child = _a[_i];
  10506. child._resolve(value);
  10507. }
  10508. this._children.length = 0;
  10509. delete this._onFulfilled;
  10510. delete this._onRejected;
  10511. }
  10512. catch (e) {
  10513. this._reject(e, true);
  10514. }
  10515. };
  10516. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10517. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10518. this._state = PromiseStates.Rejected;
  10519. this._reason = reason;
  10520. if (this._onRejected && !onLocalThrow) {
  10521. try {
  10522. this._onRejected(reason);
  10523. this._rejectWasConsumed = true;
  10524. }
  10525. catch (e) {
  10526. reason = e;
  10527. }
  10528. }
  10529. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10530. var child = _a[_i];
  10531. if (this._rejectWasConsumed) {
  10532. child._resolve(null);
  10533. }
  10534. else {
  10535. child._reject(reason);
  10536. }
  10537. }
  10538. this._children.length = 0;
  10539. delete this._onFulfilled;
  10540. delete this._onRejected;
  10541. };
  10542. InternalPromise.resolve = function (value) {
  10543. var newPromise = new InternalPromise();
  10544. newPromise._resolve(value);
  10545. return newPromise;
  10546. };
  10547. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10548. promise.then(function (value) {
  10549. agregator.results[index] = value;
  10550. agregator.count++;
  10551. if (agregator.count === agregator.target) {
  10552. agregator.rootPromise._resolve(agregator.results);
  10553. }
  10554. return null;
  10555. }, function (reason) {
  10556. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10557. agregator.rootPromise._reject(reason);
  10558. }
  10559. });
  10560. };
  10561. InternalPromise.all = function (promises) {
  10562. var newPromise = new InternalPromise();
  10563. var agregator = new FulFillmentAgregator();
  10564. agregator.target = promises.length;
  10565. agregator.rootPromise = newPromise;
  10566. if (promises.length) {
  10567. for (var index = 0; index < promises.length; index++) {
  10568. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10569. }
  10570. }
  10571. else {
  10572. newPromise._resolve([]);
  10573. }
  10574. return newPromise;
  10575. };
  10576. InternalPromise.race = function (promises) {
  10577. var newPromise = new InternalPromise();
  10578. if (promises.length) {
  10579. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10580. var promise = promises_1[_i];
  10581. promise.then(function (value) {
  10582. if (newPromise) {
  10583. newPromise._resolve(value);
  10584. newPromise = null;
  10585. }
  10586. return null;
  10587. }, function (reason) {
  10588. if (newPromise) {
  10589. newPromise._reject(reason);
  10590. newPromise = null;
  10591. }
  10592. });
  10593. }
  10594. }
  10595. return newPromise;
  10596. };
  10597. return InternalPromise;
  10598. }());
  10599. /**
  10600. * Helper class that provides a small promise polyfill
  10601. */
  10602. var PromisePolyfill = /** @class */ (function () {
  10603. function PromisePolyfill() {
  10604. }
  10605. /**
  10606. * Static function used to check if the polyfill is required
  10607. * If this is the case then the function will inject the polyfill to window.Promise
  10608. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10609. */
  10610. PromisePolyfill.Apply = function (force) {
  10611. if (force === void 0) { force = false; }
  10612. if (force || typeof Promise === 'undefined') {
  10613. var root = window;
  10614. root.Promise = InternalPromise;
  10615. }
  10616. };
  10617. return PromisePolyfill;
  10618. }());
  10619. BABYLON.PromisePolyfill = PromisePolyfill;
  10620. })(BABYLON || (BABYLON = {}));
  10621. //# sourceMappingURL=babylon.promise.js.map
  10622. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10623. var BABYLON;
  10624. (function (BABYLON) {
  10625. /**
  10626. * Helper class to push actions to a pool of workers.
  10627. */
  10628. var WorkerPool = /** @class */ (function () {
  10629. /**
  10630. * Constructor
  10631. * @param workers Array of workers to use for actions
  10632. */
  10633. function WorkerPool(workers) {
  10634. this._pendingActions = new Array();
  10635. this._workerInfos = workers.map(function (worker) { return ({
  10636. worker: worker,
  10637. active: false
  10638. }); });
  10639. }
  10640. /**
  10641. * Terminates all workers and clears any pending actions.
  10642. */
  10643. WorkerPool.prototype.dispose = function () {
  10644. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10645. var workerInfo = _a[_i];
  10646. workerInfo.worker.terminate();
  10647. }
  10648. delete this._workerInfos;
  10649. delete this._pendingActions;
  10650. };
  10651. /**
  10652. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10653. * pended until a worker has completed its action.
  10654. * @param action The action to perform. Call onComplete when the action is complete.
  10655. */
  10656. WorkerPool.prototype.push = function (action) {
  10657. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10658. var workerInfo = _a[_i];
  10659. if (!workerInfo.active) {
  10660. this._execute(workerInfo, action);
  10661. return;
  10662. }
  10663. }
  10664. this._pendingActions.push(action);
  10665. };
  10666. WorkerPool.prototype._execute = function (workerInfo, action) {
  10667. var _this = this;
  10668. workerInfo.active = true;
  10669. action(workerInfo.worker, function () {
  10670. workerInfo.active = false;
  10671. var nextAction = _this._pendingActions.shift();
  10672. if (nextAction) {
  10673. _this._execute(workerInfo, nextAction);
  10674. }
  10675. });
  10676. };
  10677. return WorkerPool;
  10678. }());
  10679. BABYLON.WorkerPool = WorkerPool;
  10680. })(BABYLON || (BABYLON = {}));
  10681. //# sourceMappingURL=babylon.workerPool.js.map
  10682. var BABYLON;
  10683. (function (BABYLON) {
  10684. /**
  10685. * @hidden
  10686. **/
  10687. var _AlphaState = /** @class */ (function () {
  10688. /**
  10689. * Initializes the state.
  10690. */
  10691. function _AlphaState() {
  10692. this._isAlphaBlendDirty = false;
  10693. this._isBlendFunctionParametersDirty = false;
  10694. this._isBlendEquationParametersDirty = false;
  10695. this._isBlendConstantsDirty = false;
  10696. this._alphaBlend = false;
  10697. this._blendFunctionParameters = new Array(4);
  10698. this._blendEquationParameters = new Array(2);
  10699. this._blendConstants = new Array(4);
  10700. this.reset();
  10701. }
  10702. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10703. get: function () {
  10704. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10705. },
  10706. enumerable: true,
  10707. configurable: true
  10708. });
  10709. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10710. get: function () {
  10711. return this._alphaBlend;
  10712. },
  10713. set: function (value) {
  10714. if (this._alphaBlend === value) {
  10715. return;
  10716. }
  10717. this._alphaBlend = value;
  10718. this._isAlphaBlendDirty = true;
  10719. },
  10720. enumerable: true,
  10721. configurable: true
  10722. });
  10723. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10724. if (this._blendConstants[0] === r &&
  10725. this._blendConstants[1] === g &&
  10726. this._blendConstants[2] === b &&
  10727. this._blendConstants[3] === a) {
  10728. return;
  10729. }
  10730. this._blendConstants[0] = r;
  10731. this._blendConstants[1] = g;
  10732. this._blendConstants[2] = b;
  10733. this._blendConstants[3] = a;
  10734. this._isBlendConstantsDirty = true;
  10735. };
  10736. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10737. if (this._blendFunctionParameters[0] === value0 &&
  10738. this._blendFunctionParameters[1] === value1 &&
  10739. this._blendFunctionParameters[2] === value2 &&
  10740. this._blendFunctionParameters[3] === value3) {
  10741. return;
  10742. }
  10743. this._blendFunctionParameters[0] = value0;
  10744. this._blendFunctionParameters[1] = value1;
  10745. this._blendFunctionParameters[2] = value2;
  10746. this._blendFunctionParameters[3] = value3;
  10747. this._isBlendFunctionParametersDirty = true;
  10748. };
  10749. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10750. if (this._blendEquationParameters[0] === rgb &&
  10751. this._blendEquationParameters[1] === alpha) {
  10752. return;
  10753. }
  10754. this._blendEquationParameters[0] = rgb;
  10755. this._blendEquationParameters[1] = alpha;
  10756. this._isBlendEquationParametersDirty = true;
  10757. };
  10758. _AlphaState.prototype.reset = function () {
  10759. this._alphaBlend = false;
  10760. this._blendFunctionParameters[0] = null;
  10761. this._blendFunctionParameters[1] = null;
  10762. this._blendFunctionParameters[2] = null;
  10763. this._blendFunctionParameters[3] = null;
  10764. this._blendEquationParameters[0] = null;
  10765. this._blendEquationParameters[1] = null;
  10766. this._blendConstants[0] = null;
  10767. this._blendConstants[1] = null;
  10768. this._blendConstants[2] = null;
  10769. this._blendConstants[3] = null;
  10770. this._isAlphaBlendDirty = true;
  10771. this._isBlendFunctionParametersDirty = false;
  10772. this._isBlendEquationParametersDirty = false;
  10773. this._isBlendConstantsDirty = false;
  10774. };
  10775. _AlphaState.prototype.apply = function (gl) {
  10776. if (!this.isDirty) {
  10777. return;
  10778. }
  10779. // Alpha blend
  10780. if (this._isAlphaBlendDirty) {
  10781. if (this._alphaBlend) {
  10782. gl.enable(gl.BLEND);
  10783. }
  10784. else {
  10785. gl.disable(gl.BLEND);
  10786. }
  10787. this._isAlphaBlendDirty = false;
  10788. }
  10789. // Alpha function
  10790. if (this._isBlendFunctionParametersDirty) {
  10791. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10792. this._isBlendFunctionParametersDirty = false;
  10793. }
  10794. // Alpha equation
  10795. if (this._isBlendEquationParametersDirty) {
  10796. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10797. this._isBlendEquationParametersDirty = false;
  10798. }
  10799. // Constants
  10800. if (this._isBlendConstantsDirty) {
  10801. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10802. this._isBlendConstantsDirty = false;
  10803. }
  10804. };
  10805. return _AlphaState;
  10806. }());
  10807. BABYLON._AlphaState = _AlphaState;
  10808. })(BABYLON || (BABYLON = {}));
  10809. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10810. var BABYLON;
  10811. (function (BABYLON) {
  10812. /**
  10813. * @hidden
  10814. **/
  10815. var _DepthCullingState = /** @class */ (function () {
  10816. /**
  10817. * Initializes the state.
  10818. */
  10819. function _DepthCullingState() {
  10820. this._isDepthTestDirty = false;
  10821. this._isDepthMaskDirty = false;
  10822. this._isDepthFuncDirty = false;
  10823. this._isCullFaceDirty = false;
  10824. this._isCullDirty = false;
  10825. this._isZOffsetDirty = false;
  10826. this._isFrontFaceDirty = false;
  10827. this.reset();
  10828. }
  10829. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10830. get: function () {
  10831. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10837. get: function () {
  10838. return this._zOffset;
  10839. },
  10840. set: function (value) {
  10841. if (this._zOffset === value) {
  10842. return;
  10843. }
  10844. this._zOffset = value;
  10845. this._isZOffsetDirty = true;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10851. get: function () {
  10852. return this._cullFace;
  10853. },
  10854. set: function (value) {
  10855. if (this._cullFace === value) {
  10856. return;
  10857. }
  10858. this._cullFace = value;
  10859. this._isCullFaceDirty = true;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10865. get: function () {
  10866. return this._cull;
  10867. },
  10868. set: function (value) {
  10869. if (this._cull === value) {
  10870. return;
  10871. }
  10872. this._cull = value;
  10873. this._isCullDirty = true;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10879. get: function () {
  10880. return this._depthFunc;
  10881. },
  10882. set: function (value) {
  10883. if (this._depthFunc === value) {
  10884. return;
  10885. }
  10886. this._depthFunc = value;
  10887. this._isDepthFuncDirty = true;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10893. get: function () {
  10894. return this._depthMask;
  10895. },
  10896. set: function (value) {
  10897. if (this._depthMask === value) {
  10898. return;
  10899. }
  10900. this._depthMask = value;
  10901. this._isDepthMaskDirty = true;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10907. get: function () {
  10908. return this._depthTest;
  10909. },
  10910. set: function (value) {
  10911. if (this._depthTest === value) {
  10912. return;
  10913. }
  10914. this._depthTest = value;
  10915. this._isDepthTestDirty = true;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10921. get: function () {
  10922. return this._frontFace;
  10923. },
  10924. set: function (value) {
  10925. if (this._frontFace === value) {
  10926. return;
  10927. }
  10928. this._frontFace = value;
  10929. this._isFrontFaceDirty = true;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. _DepthCullingState.prototype.reset = function () {
  10935. this._depthMask = true;
  10936. this._depthTest = true;
  10937. this._depthFunc = null;
  10938. this._cullFace = null;
  10939. this._cull = null;
  10940. this._zOffset = 0;
  10941. this._frontFace = null;
  10942. this._isDepthTestDirty = true;
  10943. this._isDepthMaskDirty = true;
  10944. this._isDepthFuncDirty = false;
  10945. this._isCullFaceDirty = false;
  10946. this._isCullDirty = false;
  10947. this._isZOffsetDirty = false;
  10948. this._isFrontFaceDirty = false;
  10949. };
  10950. _DepthCullingState.prototype.apply = function (gl) {
  10951. if (!this.isDirty) {
  10952. return;
  10953. }
  10954. // Cull
  10955. if (this._isCullDirty) {
  10956. if (this.cull) {
  10957. gl.enable(gl.CULL_FACE);
  10958. }
  10959. else {
  10960. gl.disable(gl.CULL_FACE);
  10961. }
  10962. this._isCullDirty = false;
  10963. }
  10964. // Cull face
  10965. if (this._isCullFaceDirty) {
  10966. gl.cullFace(this.cullFace);
  10967. this._isCullFaceDirty = false;
  10968. }
  10969. // Depth mask
  10970. if (this._isDepthMaskDirty) {
  10971. gl.depthMask(this.depthMask);
  10972. this._isDepthMaskDirty = false;
  10973. }
  10974. // Depth test
  10975. if (this._isDepthTestDirty) {
  10976. if (this.depthTest) {
  10977. gl.enable(gl.DEPTH_TEST);
  10978. }
  10979. else {
  10980. gl.disable(gl.DEPTH_TEST);
  10981. }
  10982. this._isDepthTestDirty = false;
  10983. }
  10984. // Depth func
  10985. if (this._isDepthFuncDirty) {
  10986. gl.depthFunc(this.depthFunc);
  10987. this._isDepthFuncDirty = false;
  10988. }
  10989. // zOffset
  10990. if (this._isZOffsetDirty) {
  10991. if (this.zOffset) {
  10992. gl.enable(gl.POLYGON_OFFSET_FILL);
  10993. gl.polygonOffset(this.zOffset, 0);
  10994. }
  10995. else {
  10996. gl.disable(gl.POLYGON_OFFSET_FILL);
  10997. }
  10998. this._isZOffsetDirty = false;
  10999. }
  11000. // Front face
  11001. if (this._isFrontFaceDirty) {
  11002. gl.frontFace(this.frontFace);
  11003. this._isFrontFaceDirty = false;
  11004. }
  11005. };
  11006. return _DepthCullingState;
  11007. }());
  11008. BABYLON._DepthCullingState = _DepthCullingState;
  11009. })(BABYLON || (BABYLON = {}));
  11010. //# sourceMappingURL=babylon.depthCullingState.js.map
  11011. var BABYLON;
  11012. (function (BABYLON) {
  11013. /**
  11014. * @hidden
  11015. **/
  11016. var _StencilState = /** @class */ (function () {
  11017. function _StencilState() {
  11018. this._isStencilTestDirty = false;
  11019. this._isStencilMaskDirty = false;
  11020. this._isStencilFuncDirty = false;
  11021. this._isStencilOpDirty = false;
  11022. this.reset();
  11023. }
  11024. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11025. get: function () {
  11026. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11032. get: function () {
  11033. return this._stencilFunc;
  11034. },
  11035. set: function (value) {
  11036. if (this._stencilFunc === value) {
  11037. return;
  11038. }
  11039. this._stencilFunc = value;
  11040. this._isStencilFuncDirty = true;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11046. get: function () {
  11047. return this._stencilFuncRef;
  11048. },
  11049. set: function (value) {
  11050. if (this._stencilFuncRef === value) {
  11051. return;
  11052. }
  11053. this._stencilFuncRef = value;
  11054. this._isStencilFuncDirty = true;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11060. get: function () {
  11061. return this._stencilFuncMask;
  11062. },
  11063. set: function (value) {
  11064. if (this._stencilFuncMask === value) {
  11065. return;
  11066. }
  11067. this._stencilFuncMask = value;
  11068. this._isStencilFuncDirty = true;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11074. get: function () {
  11075. return this._stencilOpStencilFail;
  11076. },
  11077. set: function (value) {
  11078. if (this._stencilOpStencilFail === value) {
  11079. return;
  11080. }
  11081. this._stencilOpStencilFail = value;
  11082. this._isStencilOpDirty = true;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11088. get: function () {
  11089. return this._stencilOpDepthFail;
  11090. },
  11091. set: function (value) {
  11092. if (this._stencilOpDepthFail === value) {
  11093. return;
  11094. }
  11095. this._stencilOpDepthFail = value;
  11096. this._isStencilOpDirty = true;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11102. get: function () {
  11103. return this._stencilOpStencilDepthPass;
  11104. },
  11105. set: function (value) {
  11106. if (this._stencilOpStencilDepthPass === value) {
  11107. return;
  11108. }
  11109. this._stencilOpStencilDepthPass = value;
  11110. this._isStencilOpDirty = true;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11116. get: function () {
  11117. return this._stencilMask;
  11118. },
  11119. set: function (value) {
  11120. if (this._stencilMask === value) {
  11121. return;
  11122. }
  11123. this._stencilMask = value;
  11124. this._isStencilMaskDirty = true;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11130. get: function () {
  11131. return this._stencilTest;
  11132. },
  11133. set: function (value) {
  11134. if (this._stencilTest === value) {
  11135. return;
  11136. }
  11137. this._stencilTest = value;
  11138. this._isStencilTestDirty = true;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. _StencilState.prototype.reset = function () {
  11144. this._stencilTest = false;
  11145. this._stencilMask = 0xFF;
  11146. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11147. this._stencilFuncRef = 1;
  11148. this._stencilFuncMask = 0xFF;
  11149. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11150. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11151. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11152. this._isStencilTestDirty = true;
  11153. this._isStencilMaskDirty = true;
  11154. this._isStencilFuncDirty = true;
  11155. this._isStencilOpDirty = true;
  11156. };
  11157. _StencilState.prototype.apply = function (gl) {
  11158. if (!this.isDirty) {
  11159. return;
  11160. }
  11161. // Stencil test
  11162. if (this._isStencilTestDirty) {
  11163. if (this.stencilTest) {
  11164. gl.enable(gl.STENCIL_TEST);
  11165. }
  11166. else {
  11167. gl.disable(gl.STENCIL_TEST);
  11168. }
  11169. this._isStencilTestDirty = false;
  11170. }
  11171. // Stencil mask
  11172. if (this._isStencilMaskDirty) {
  11173. gl.stencilMask(this.stencilMask);
  11174. this._isStencilMaskDirty = false;
  11175. }
  11176. // Stencil func
  11177. if (this._isStencilFuncDirty) {
  11178. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11179. this._isStencilFuncDirty = false;
  11180. }
  11181. // Stencil op
  11182. if (this._isStencilOpDirty) {
  11183. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11184. this._isStencilOpDirty = false;
  11185. }
  11186. };
  11187. return _StencilState;
  11188. }());
  11189. BABYLON._StencilState = _StencilState;
  11190. })(BABYLON || (BABYLON = {}));
  11191. //# sourceMappingURL=babylon.stencilState.js.map
  11192. var __assign = (this && this.__assign) || function () {
  11193. __assign = Object.assign || function(t) {
  11194. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11195. s = arguments[i];
  11196. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11197. t[p] = s[p];
  11198. }
  11199. return t;
  11200. };
  11201. return __assign.apply(this, arguments);
  11202. };
  11203. var BABYLON;
  11204. (function (BABYLON) {
  11205. /**
  11206. * Keeps track of all the buffer info used in engine.
  11207. */
  11208. var BufferPointer = /** @class */ (function () {
  11209. function BufferPointer() {
  11210. }
  11211. return BufferPointer;
  11212. }());
  11213. /**
  11214. * Interface for attribute information associated with buffer instanciation
  11215. */
  11216. var InstancingAttributeInfo = /** @class */ (function () {
  11217. function InstancingAttributeInfo() {
  11218. }
  11219. return InstancingAttributeInfo;
  11220. }());
  11221. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11222. /**
  11223. * Define options used to create a render target texture
  11224. */
  11225. var RenderTargetCreationOptions = /** @class */ (function () {
  11226. function RenderTargetCreationOptions() {
  11227. }
  11228. return RenderTargetCreationOptions;
  11229. }());
  11230. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11231. /**
  11232. * Define options used to create a depth texture
  11233. */
  11234. var DepthTextureCreationOptions = /** @class */ (function () {
  11235. function DepthTextureCreationOptions() {
  11236. }
  11237. return DepthTextureCreationOptions;
  11238. }());
  11239. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11240. /**
  11241. * Class used to describe the capabilities of the engine relatively to the current browser
  11242. */
  11243. var EngineCapabilities = /** @class */ (function () {
  11244. function EngineCapabilities() {
  11245. }
  11246. return EngineCapabilities;
  11247. }());
  11248. BABYLON.EngineCapabilities = EngineCapabilities;
  11249. /**
  11250. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11251. */
  11252. var Engine = /** @class */ (function () {
  11253. /**
  11254. * Creates a new engine
  11255. * @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
  11256. * @param antialias defines enable antialiasing (default: false)
  11257. * @param options defines further options to be sent to the getContext() function
  11258. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11259. */
  11260. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11261. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11262. var _this = this;
  11263. // Public members
  11264. /**
  11265. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11266. */
  11267. this.forcePOTTextures = false;
  11268. /**
  11269. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11270. */
  11271. this.isFullscreen = false;
  11272. /**
  11273. * Gets a boolean indicating if the pointer is currently locked
  11274. */
  11275. this.isPointerLock = false;
  11276. /**
  11277. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11278. */
  11279. this.cullBackFaces = true;
  11280. /**
  11281. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11282. */
  11283. this.renderEvenInBackground = true;
  11284. /**
  11285. * Gets or sets a boolean indicating that cache can be kept between frames
  11286. */
  11287. this.preventCacheWipeBetweenFrames = false;
  11288. /**
  11289. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11290. **/
  11291. this.enableOfflineSupport = false;
  11292. /**
  11293. * 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)
  11294. **/
  11295. this.disableManifestCheck = false;
  11296. /**
  11297. * Gets the list of created scenes
  11298. */
  11299. this.scenes = new Array();
  11300. /**
  11301. * Gets the list of created postprocesses
  11302. */
  11303. this.postProcesses = new Array();
  11304. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11305. this.validateShaderPrograms = false;
  11306. // Observables
  11307. /**
  11308. * Observable event triggered each time the rendering canvas is resized
  11309. */
  11310. this.onResizeObservable = new BABYLON.Observable();
  11311. /**
  11312. * Observable event triggered each time the canvas loses focus
  11313. */
  11314. this.onCanvasBlurObservable = new BABYLON.Observable();
  11315. /**
  11316. * Observable event triggered each time the canvas gains focus
  11317. */
  11318. this.onCanvasFocusObservable = new BABYLON.Observable();
  11319. /**
  11320. * Observable event triggered each time the canvas receives pointerout event
  11321. */
  11322. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11323. /**
  11324. * Observable event triggered before each texture is initialized
  11325. */
  11326. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11327. //WebVR
  11328. this._vrDisplay = undefined;
  11329. this._vrSupported = false;
  11330. this._vrExclusivePointerMode = false;
  11331. // Uniform buffers list
  11332. /**
  11333. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11334. */
  11335. this.disableUniformBuffers = false;
  11336. /** @hidden */
  11337. this._uniformBuffers = new Array();
  11338. // Observables
  11339. /**
  11340. * Observable raised when the engine begins a new frame
  11341. */
  11342. this.onBeginFrameObservable = new BABYLON.Observable();
  11343. /**
  11344. * Observable raised when the engine ends the current frame
  11345. */
  11346. this.onEndFrameObservable = new BABYLON.Observable();
  11347. /**
  11348. * Observable raised when the engine is about to compile a shader
  11349. */
  11350. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11351. /**
  11352. * Observable raised when the engine has jsut compiled a shader
  11353. */
  11354. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11355. this._windowIsBackground = false;
  11356. this._webGLVersion = 1.0;
  11357. /** @hidden */
  11358. this._badOS = false;
  11359. /** @hidden */
  11360. this._badDesktopOS = false;
  11361. /**
  11362. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11363. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11364. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11365. */
  11366. this.disableTextureBindingOptimization = false;
  11367. /**
  11368. * Observable signaled when VR display mode changes
  11369. */
  11370. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11371. /**
  11372. * Observable signaled when VR request present is complete
  11373. */
  11374. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11375. /**
  11376. * Observable signaled when VR request present starts
  11377. */
  11378. this.onVRRequestPresentStart = new BABYLON.Observable();
  11379. this._colorWrite = true;
  11380. /** @hidden */
  11381. this._drawCalls = new BABYLON.PerfCounter();
  11382. /** @hidden */
  11383. this._textureCollisions = new BABYLON.PerfCounter();
  11384. this._renderingQueueLaunched = false;
  11385. this._activeRenderLoops = new Array();
  11386. // Deterministic lockstepMaxSteps
  11387. this._deterministicLockstep = false;
  11388. this._lockstepMaxSteps = 4;
  11389. // Lost context
  11390. /**
  11391. * Observable signaled when a context lost event is raised
  11392. */
  11393. this.onContextLostObservable = new BABYLON.Observable();
  11394. /**
  11395. * Observable signaled when a context restored event is raised
  11396. */
  11397. this.onContextRestoredObservable = new BABYLON.Observable();
  11398. this._contextWasLost = false;
  11399. this._doNotHandleContextLost = false;
  11400. // FPS
  11401. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11402. this._fps = 60;
  11403. this._deltaTime = 0;
  11404. /**
  11405. * Turn this value on if you want to pause FPS computation when in background
  11406. */
  11407. this.disablePerformanceMonitorInBackground = false;
  11408. // States
  11409. /** @hidden */
  11410. this._depthCullingState = new BABYLON._DepthCullingState();
  11411. /** @hidden */
  11412. this._stencilState = new BABYLON._StencilState();
  11413. /** @hidden */
  11414. this._alphaState = new BABYLON._AlphaState();
  11415. /** @hidden */
  11416. this._alphaMode = Engine.ALPHA_DISABLE;
  11417. // Cache
  11418. this._internalTexturesCache = new Array();
  11419. /** @hidden */
  11420. this._activeChannel = 0;
  11421. this._currentTextureChannel = -1;
  11422. /** @hidden */
  11423. this._boundTexturesCache = {};
  11424. this._compiledEffects = {};
  11425. this._vertexAttribArraysEnabled = [];
  11426. this._uintIndicesCurrentlySet = false;
  11427. this._currentBoundBuffer = new Array();
  11428. /** @hidden */
  11429. this._currentFramebuffer = null;
  11430. this._currentBufferPointers = new Array();
  11431. this._currentInstanceLocations = new Array();
  11432. this._currentInstanceBuffers = new Array();
  11433. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11434. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11435. this._vaoRecordInProgress = false;
  11436. this._mustWipeVertexAttributes = false;
  11437. this._nextFreeTextureSlots = new Array();
  11438. this._maxSimultaneousTextures = 0;
  11439. this._activeRequests = new Array();
  11440. // Hardware supported Compressed Textures
  11441. this._texturesSupported = new Array();
  11442. /**
  11443. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11444. */
  11445. this.premultipliedAlpha = true;
  11446. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11447. this._onVRFullScreenTriggered = function () {
  11448. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11449. //get the old size before we change
  11450. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11451. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11452. //get the width and height, change the render size
  11453. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11454. _this.setHardwareScalingLevel(1);
  11455. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11456. }
  11457. else {
  11458. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11459. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11460. }
  11461. };
  11462. this._unpackFlipYCached = null;
  11463. this._boundUniforms = {};
  11464. // Register promises
  11465. BABYLON.PromisePolyfill.Apply();
  11466. var canvas = null;
  11467. Engine.Instances.push(this);
  11468. if (!canvasOrContext) {
  11469. return;
  11470. }
  11471. options = options || {};
  11472. if (canvasOrContext.getContext) {
  11473. canvas = canvasOrContext;
  11474. this._renderingCanvas = canvas;
  11475. if (antialias != null) {
  11476. options.antialias = antialias;
  11477. }
  11478. if (options.deterministicLockstep === undefined) {
  11479. options.deterministicLockstep = false;
  11480. }
  11481. if (options.lockstepMaxSteps === undefined) {
  11482. options.lockstepMaxSteps = 4;
  11483. }
  11484. if (options.preserveDrawingBuffer === undefined) {
  11485. options.preserveDrawingBuffer = false;
  11486. }
  11487. if (options.audioEngine === undefined) {
  11488. options.audioEngine = true;
  11489. }
  11490. if (options.stencil === undefined) {
  11491. options.stencil = true;
  11492. }
  11493. if (options.premultipliedAlpha === false) {
  11494. this.premultipliedAlpha = false;
  11495. }
  11496. this._deterministicLockstep = options.deterministicLockstep;
  11497. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11498. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11499. // Exceptions
  11500. if (navigator && navigator.userAgent) {
  11501. var ua = navigator.userAgent;
  11502. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11503. var exception = _a[_i];
  11504. var key = exception.key;
  11505. var targets = exception.targets;
  11506. if (ua.indexOf(key) > -1) {
  11507. if (exception.capture && exception.captureConstraint) {
  11508. var capture = exception.capture;
  11509. var constraint = exception.captureConstraint;
  11510. var regex = new RegExp(capture);
  11511. var matches = regex.exec(ua);
  11512. if (matches && matches.length > 0) {
  11513. var capturedValue = parseInt(matches[matches.length - 1]);
  11514. if (capturedValue >= constraint) {
  11515. continue;
  11516. }
  11517. }
  11518. }
  11519. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11520. var target = targets_1[_b];
  11521. switch (target) {
  11522. case "uniformBuffer":
  11523. this.disableUniformBuffers = true;
  11524. break;
  11525. case "textureBindingOptimization":
  11526. this.disableTextureBindingOptimization = true;
  11527. break;
  11528. }
  11529. }
  11530. }
  11531. }
  11532. }
  11533. // GL
  11534. if (!options.disableWebGL2Support) {
  11535. try {
  11536. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11537. if (this._gl) {
  11538. this._webGLVersion = 2.0;
  11539. }
  11540. }
  11541. catch (e) {
  11542. // Do nothing
  11543. }
  11544. }
  11545. if (!this._gl) {
  11546. if (!canvas) {
  11547. throw new Error("The provided canvas is null or undefined.");
  11548. }
  11549. try {
  11550. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11551. }
  11552. catch (e) {
  11553. throw new Error("WebGL not supported");
  11554. }
  11555. }
  11556. if (!this._gl) {
  11557. throw new Error("WebGL not supported");
  11558. }
  11559. this._onCanvasFocus = function () {
  11560. _this.onCanvasFocusObservable.notifyObservers(_this);
  11561. };
  11562. this._onCanvasBlur = function () {
  11563. _this.onCanvasBlurObservable.notifyObservers(_this);
  11564. };
  11565. canvas.addEventListener("focus", this._onCanvasFocus);
  11566. canvas.addEventListener("blur", this._onCanvasBlur);
  11567. this._onBlur = function () {
  11568. if (_this.disablePerformanceMonitorInBackground) {
  11569. _this._performanceMonitor.disable();
  11570. }
  11571. _this._windowIsBackground = true;
  11572. };
  11573. this._onFocus = function () {
  11574. if (_this.disablePerformanceMonitorInBackground) {
  11575. _this._performanceMonitor.enable();
  11576. }
  11577. _this._windowIsBackground = false;
  11578. };
  11579. this._onCanvasPointerOut = function (ev) {
  11580. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11581. };
  11582. window.addEventListener("blur", this._onBlur);
  11583. window.addEventListener("focus", this._onFocus);
  11584. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11585. // Context lost
  11586. if (!this._doNotHandleContextLost) {
  11587. this._onContextLost = function (evt) {
  11588. evt.preventDefault();
  11589. _this._contextWasLost = true;
  11590. BABYLON.Tools.Warn("WebGL context lost.");
  11591. _this.onContextLostObservable.notifyObservers(_this);
  11592. };
  11593. this._onContextRestored = function (evt) {
  11594. // Adding a timeout to avoid race condition at browser level
  11595. setTimeout(function () {
  11596. // Rebuild gl context
  11597. _this._initGLContext();
  11598. // Rebuild effects
  11599. _this._rebuildEffects();
  11600. // Rebuild textures
  11601. _this._rebuildInternalTextures();
  11602. // Rebuild buffers
  11603. _this._rebuildBuffers();
  11604. // Cache
  11605. _this.wipeCaches(true);
  11606. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11607. _this.onContextRestoredObservable.notifyObservers(_this);
  11608. _this._contextWasLost = false;
  11609. }, 0);
  11610. };
  11611. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11612. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11613. }
  11614. }
  11615. else {
  11616. this._gl = canvasOrContext;
  11617. this._renderingCanvas = this._gl.canvas;
  11618. if (this._gl.renderbufferStorageMultisample) {
  11619. this._webGLVersion = 2.0;
  11620. }
  11621. options.stencil = this._gl.getContextAttributes().stencil;
  11622. }
  11623. // Viewport
  11624. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11625. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11626. this.resize();
  11627. this._isStencilEnable = options.stencil ? true : false;
  11628. this._initGLContext();
  11629. if (canvas) {
  11630. // Fullscreen
  11631. this._onFullscreenChange = function () {
  11632. if (document.fullscreen !== undefined) {
  11633. _this.isFullscreen = document.fullscreen;
  11634. }
  11635. else if (document.mozFullScreen !== undefined) {
  11636. _this.isFullscreen = document.mozFullScreen;
  11637. }
  11638. else if (document.webkitIsFullScreen !== undefined) {
  11639. _this.isFullscreen = document.webkitIsFullScreen;
  11640. }
  11641. else if (document.msIsFullScreen !== undefined) {
  11642. _this.isFullscreen = document.msIsFullScreen;
  11643. }
  11644. // Pointer lock
  11645. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11646. canvas.requestPointerLock = canvas.requestPointerLock ||
  11647. canvas.msRequestPointerLock ||
  11648. canvas.mozRequestPointerLock ||
  11649. canvas.webkitRequestPointerLock;
  11650. if (canvas.requestPointerLock) {
  11651. canvas.requestPointerLock();
  11652. }
  11653. }
  11654. };
  11655. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11656. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11657. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11658. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11659. // Pointer lock
  11660. this._onPointerLockChange = function () {
  11661. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11662. document.webkitPointerLockElement === canvas ||
  11663. document.msPointerLockElement === canvas ||
  11664. document.pointerLockElement === canvas);
  11665. };
  11666. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11667. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11668. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11669. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11670. this._onVRDisplayPointerRestricted = function () {
  11671. if (canvas) {
  11672. canvas.requestPointerLock();
  11673. }
  11674. };
  11675. this._onVRDisplayPointerUnrestricted = function () {
  11676. document.exitPointerLock();
  11677. };
  11678. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11679. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11680. }
  11681. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11682. Engine.audioEngine = new BABYLON.AudioEngine();
  11683. }
  11684. // Prepare buffer pointers
  11685. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11686. this._currentBufferPointers[i] = new BufferPointer();
  11687. }
  11688. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11689. // Load WebVR Devices
  11690. if (options.autoEnableWebVR) {
  11691. this.initWebVR();
  11692. }
  11693. // Detect if we are running on a faulty buggy OS.
  11694. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11695. // Detect if we are running on a faulty buggy desktop OS.
  11696. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11697. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11698. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11699. }
  11700. Object.defineProperty(Engine, "LastCreatedEngine", {
  11701. /**
  11702. * Gets the latest created engine
  11703. */
  11704. get: function () {
  11705. if (Engine.Instances.length === 0) {
  11706. return null;
  11707. }
  11708. return Engine.Instances[Engine.Instances.length - 1];
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(Engine, "LastCreatedScene", {
  11714. /**
  11715. * Gets the latest created scene
  11716. */
  11717. get: function () {
  11718. var lastCreatedEngine = Engine.LastCreatedEngine;
  11719. if (!lastCreatedEngine) {
  11720. return null;
  11721. }
  11722. if (lastCreatedEngine.scenes.length === 0) {
  11723. return null;
  11724. }
  11725. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. /**
  11731. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11732. * @param flag defines which part of the materials must be marked as dirty
  11733. * @param predicate defines a predicate used to filter which materials should be affected
  11734. */
  11735. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11736. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11737. var engine = Engine.Instances[engineIndex];
  11738. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11739. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11740. }
  11741. }
  11742. };
  11743. Object.defineProperty(Engine, "Version", {
  11744. /**
  11745. * Returns the current version of the framework
  11746. */
  11747. get: function () {
  11748. return "3.3.0-beta.3";
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11754. /**
  11755. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11756. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11757. */
  11758. get: function () {
  11759. return this._vrExclusivePointerMode;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11765. /**
  11766. * Gets a boolean indicating that the engine supports uniform buffers
  11767. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11768. */
  11769. get: function () {
  11770. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11776. /**
  11777. * Gets a boolean indicating that only power of 2 textures are supported
  11778. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11779. */
  11780. get: function () {
  11781. return this._webGLVersion < 2 || this.forcePOTTextures;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11787. /**
  11788. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11789. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11790. */
  11791. get: function () {
  11792. return this._doNotHandleContextLost;
  11793. },
  11794. set: function (value) {
  11795. this._doNotHandleContextLost = value;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11801. /**
  11802. * Gets the performance monitor attached to this engine
  11803. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11804. */
  11805. get: function () {
  11806. return this._performanceMonitor;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11812. /**
  11813. * Gets the list of texture formats supported
  11814. */
  11815. get: function () {
  11816. return this._texturesSupported;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11822. /**
  11823. * Gets the list of texture formats in use
  11824. */
  11825. get: function () {
  11826. return this._textureFormatInUse;
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(Engine.prototype, "currentViewport", {
  11832. /**
  11833. * Gets the current viewport
  11834. */
  11835. get: function () {
  11836. return this._cachedViewport;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11842. /**
  11843. * Gets the default empty texture
  11844. */
  11845. get: function () {
  11846. if (!this._emptyTexture) {
  11847. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11848. }
  11849. return this._emptyTexture;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11855. /**
  11856. * Gets the default empty 3D texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyTexture3D) {
  11860. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11861. }
  11862. return this._emptyTexture3D;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11868. /**
  11869. * Gets the default empty cube texture
  11870. */
  11871. get: function () {
  11872. if (!this._emptyCubeTexture) {
  11873. var faceData = new Uint8Array(4);
  11874. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11875. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11876. }
  11877. return this._emptyCubeTexture;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Engine.prototype._rebuildInternalTextures = function () {
  11883. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11884. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11885. var internalTexture = currentState_1[_i];
  11886. internalTexture._rebuild();
  11887. }
  11888. };
  11889. Engine.prototype._rebuildEffects = function () {
  11890. for (var key in this._compiledEffects) {
  11891. var effect = this._compiledEffects[key];
  11892. effect._prepareEffect();
  11893. }
  11894. BABYLON.Effect.ResetCache();
  11895. };
  11896. Engine.prototype._rebuildBuffers = function () {
  11897. // Index / Vertex
  11898. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11899. var scene = _a[_i];
  11900. scene.resetCachedMaterial();
  11901. scene._rebuildGeometries();
  11902. scene._rebuildTextures();
  11903. }
  11904. // Uniforms
  11905. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11906. var uniformBuffer = _c[_b];
  11907. uniformBuffer._rebuild();
  11908. }
  11909. };
  11910. Engine.prototype._initGLContext = function () {
  11911. // Caps
  11912. this._caps = new EngineCapabilities();
  11913. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11914. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11915. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11916. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11917. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11918. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11919. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11920. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11921. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11922. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11923. // Infos
  11924. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11925. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11926. if (rendererInfo != null) {
  11927. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11928. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11929. }
  11930. if (!this._glVendor) {
  11931. this._glVendor = "Unknown vendor";
  11932. }
  11933. if (!this._glRenderer) {
  11934. this._glRenderer = "Unknown renderer";
  11935. }
  11936. // Constants
  11937. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11938. if (this._gl.RGBA16F !== 0x881A) {
  11939. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11940. }
  11941. if (this._gl.RGBA32F !== 0x8814) {
  11942. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11943. }
  11944. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11945. this._gl.DEPTH24_STENCIL8 = 35056;
  11946. }
  11947. // Extensions
  11948. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11949. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11950. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11951. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11952. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11953. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11954. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11955. 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');
  11956. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11957. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11958. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11959. this._caps.highPrecisionShaderSupported = true;
  11960. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11961. if (this._caps.timerQuery) {
  11962. if (this._webGLVersion === 1) {
  11963. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11964. }
  11965. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11966. }
  11967. // Checks if some of the format renders first to allow the use of webgl inspector.
  11968. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11969. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11970. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11971. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11972. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11973. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11974. if (this._webGLVersion > 1) {
  11975. this._gl.HALF_FLOAT_OES = 0x140B;
  11976. }
  11977. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11978. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11979. // Draw buffers
  11980. if (this._webGLVersion > 1) {
  11981. this._caps.drawBuffersExtension = true;
  11982. }
  11983. else {
  11984. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11985. if (drawBuffersExtension !== null) {
  11986. this._caps.drawBuffersExtension = true;
  11987. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11988. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11989. for (var i = 0; i < 16; i++) {
  11990. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11991. }
  11992. }
  11993. else {
  11994. this._caps.drawBuffersExtension = false;
  11995. }
  11996. }
  11997. // Depth Texture
  11998. if (this._webGLVersion > 1) {
  11999. this._caps.depthTextureExtension = true;
  12000. }
  12001. else {
  12002. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12003. if (depthTextureExtension != null) {
  12004. this._caps.depthTextureExtension = true;
  12005. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12006. }
  12007. }
  12008. // Vertex array object
  12009. if (this._webGLVersion > 1) {
  12010. this._caps.vertexArrayObject = true;
  12011. }
  12012. else {
  12013. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12014. if (vertexArrayObjectExtension != null) {
  12015. this._caps.vertexArrayObject = true;
  12016. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12017. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12018. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12019. }
  12020. else {
  12021. this._caps.vertexArrayObject = false;
  12022. }
  12023. }
  12024. // Instances count
  12025. if (this._webGLVersion > 1) {
  12026. this._caps.instancedArrays = true;
  12027. }
  12028. else {
  12029. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12030. if (instanceExtension != null) {
  12031. this._caps.instancedArrays = true;
  12032. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12033. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12034. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12035. }
  12036. else {
  12037. this._caps.instancedArrays = false;
  12038. }
  12039. }
  12040. // Intelligently add supported compressed formats in order to check for.
  12041. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12042. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12043. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12044. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12045. if (this._caps.astc)
  12046. this.texturesSupported.push('-astc.ktx');
  12047. if (this._caps.s3tc)
  12048. this.texturesSupported.push('-dxt.ktx');
  12049. if (this._caps.pvrtc)
  12050. this.texturesSupported.push('-pvrtc.ktx');
  12051. if (this._caps.etc2)
  12052. this.texturesSupported.push('-etc2.ktx');
  12053. if (this._caps.etc1)
  12054. this.texturesSupported.push('-etc1.ktx');
  12055. if (this._gl.getShaderPrecisionFormat) {
  12056. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12057. if (highp) {
  12058. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12059. }
  12060. }
  12061. // Depth buffer
  12062. this.setDepthBuffer(true);
  12063. this.setDepthFunctionToLessOrEqual();
  12064. this.setDepthWrite(true);
  12065. // Texture maps
  12066. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12067. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12068. this._nextFreeTextureSlots.push(slot);
  12069. }
  12070. };
  12071. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12072. /**
  12073. * Gets version of the current webGL context
  12074. */
  12075. get: function () {
  12076. return this._webGLVersion;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12082. /**
  12083. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12084. */
  12085. get: function () {
  12086. return this._isStencilEnable;
  12087. },
  12088. enumerable: true,
  12089. configurable: true
  12090. });
  12091. Engine.prototype._prepareWorkingCanvas = function () {
  12092. if (this._workingCanvas) {
  12093. return;
  12094. }
  12095. this._workingCanvas = document.createElement("canvas");
  12096. var context = this._workingCanvas.getContext("2d");
  12097. if (context) {
  12098. this._workingContext = context;
  12099. }
  12100. };
  12101. /**
  12102. * Reset the texture cache to empty state
  12103. */
  12104. Engine.prototype.resetTextureCache = function () {
  12105. for (var key in this._boundTexturesCache) {
  12106. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12107. continue;
  12108. }
  12109. var boundTexture = this._boundTexturesCache[key];
  12110. if (boundTexture) {
  12111. this._removeDesignatedSlot(boundTexture);
  12112. }
  12113. this._boundTexturesCache[key] = null;
  12114. }
  12115. if (!this.disableTextureBindingOptimization) {
  12116. this._nextFreeTextureSlots = [];
  12117. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12118. this._nextFreeTextureSlots.push(slot);
  12119. }
  12120. }
  12121. this._currentTextureChannel = -1;
  12122. };
  12123. /**
  12124. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12125. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12126. * @returns true if engine is in deterministic lock step mode
  12127. */
  12128. Engine.prototype.isDeterministicLockStep = function () {
  12129. return this._deterministicLockstep;
  12130. };
  12131. /**
  12132. * Gets the max steps when engine is running in deterministic lock step
  12133. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12134. * @returns the max steps
  12135. */
  12136. Engine.prototype.getLockstepMaxSteps = function () {
  12137. return this._lockstepMaxSteps;
  12138. };
  12139. /**
  12140. * Gets an object containing information about the current webGL context
  12141. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12142. */
  12143. Engine.prototype.getGlInfo = function () {
  12144. return {
  12145. vendor: this._glVendor,
  12146. renderer: this._glRenderer,
  12147. version: this._glVersion
  12148. };
  12149. };
  12150. /**
  12151. * Gets current aspect ratio
  12152. * @param camera defines the camera to use to get the aspect ratio
  12153. * @param useScreen defines if screen size must be used (or the current render target if any)
  12154. * @returns a number defining the aspect ratio
  12155. */
  12156. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12157. if (useScreen === void 0) { useScreen = false; }
  12158. var viewport = camera.viewport;
  12159. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12160. };
  12161. /**
  12162. * Gets current screen aspect ratio
  12163. * @returns a number defining the aspect ratio
  12164. */
  12165. Engine.prototype.getScreenAspectRatio = function () {
  12166. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12167. };
  12168. /**
  12169. * Gets the current render width
  12170. * @param useScreen defines if screen size must be used (or the current render target if any)
  12171. * @returns a number defining the current render width
  12172. */
  12173. Engine.prototype.getRenderWidth = function (useScreen) {
  12174. if (useScreen === void 0) { useScreen = false; }
  12175. if (!useScreen && this._currentRenderTarget) {
  12176. return this._currentRenderTarget.width;
  12177. }
  12178. return this._gl.drawingBufferWidth;
  12179. };
  12180. /**
  12181. * Gets the current render height
  12182. * @param useScreen defines if screen size must be used (or the current render target if any)
  12183. * @returns a number defining the current render height
  12184. */
  12185. Engine.prototype.getRenderHeight = function (useScreen) {
  12186. if (useScreen === void 0) { useScreen = false; }
  12187. if (!useScreen && this._currentRenderTarget) {
  12188. return this._currentRenderTarget.height;
  12189. }
  12190. return this._gl.drawingBufferHeight;
  12191. };
  12192. /**
  12193. * Gets the HTML canvas attached with the current webGL context
  12194. * @returns a HTML canvas
  12195. */
  12196. Engine.prototype.getRenderingCanvas = function () {
  12197. return this._renderingCanvas;
  12198. };
  12199. /**
  12200. * Gets the client rect of the HTML canvas attached with the current webGL context
  12201. * @returns a client rectanglee
  12202. */
  12203. Engine.prototype.getRenderingCanvasClientRect = function () {
  12204. if (!this._renderingCanvas) {
  12205. return null;
  12206. }
  12207. return this._renderingCanvas.getBoundingClientRect();
  12208. };
  12209. /**
  12210. * Defines the hardware scaling level.
  12211. * By default the hardware scaling level is computed from the window device ratio.
  12212. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12213. * @param level defines the level to use
  12214. */
  12215. Engine.prototype.setHardwareScalingLevel = function (level) {
  12216. this._hardwareScalingLevel = level;
  12217. this.resize();
  12218. };
  12219. /**
  12220. * Gets the current hardware scaling level.
  12221. * By default the hardware scaling level is computed from the window device ratio.
  12222. * 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.
  12223. * @returns a number indicating the current hardware scaling level
  12224. */
  12225. Engine.prototype.getHardwareScalingLevel = function () {
  12226. return this._hardwareScalingLevel;
  12227. };
  12228. /**
  12229. * Gets the list of loaded textures
  12230. * @returns an array containing all loaded textures
  12231. */
  12232. Engine.prototype.getLoadedTexturesCache = function () {
  12233. return this._internalTexturesCache;
  12234. };
  12235. /**
  12236. * Gets the object containing all engine capabilities
  12237. * @returns the EngineCapabilities object
  12238. */
  12239. Engine.prototype.getCaps = function () {
  12240. return this._caps;
  12241. };
  12242. Object.defineProperty(Engine.prototype, "drawCalls", {
  12243. /** @hidden */
  12244. get: function () {
  12245. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12246. return 0;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12252. /** @hidden */
  12253. get: function () {
  12254. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12255. return null;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. /**
  12261. * Gets the current depth function
  12262. * @returns a number defining the depth function
  12263. */
  12264. Engine.prototype.getDepthFunction = function () {
  12265. return this._depthCullingState.depthFunc;
  12266. };
  12267. /**
  12268. * Sets the current depth function
  12269. * @param depthFunc defines the function to use
  12270. */
  12271. Engine.prototype.setDepthFunction = function (depthFunc) {
  12272. this._depthCullingState.depthFunc = depthFunc;
  12273. };
  12274. /**
  12275. * Sets the current depth function to GREATER
  12276. */
  12277. Engine.prototype.setDepthFunctionToGreater = function () {
  12278. this._depthCullingState.depthFunc = this._gl.GREATER;
  12279. };
  12280. /**
  12281. * Sets the current depth function to GEQUAL
  12282. */
  12283. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12284. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12285. };
  12286. /**
  12287. * Sets the current depth function to LESS
  12288. */
  12289. Engine.prototype.setDepthFunctionToLess = function () {
  12290. this._depthCullingState.depthFunc = this._gl.LESS;
  12291. };
  12292. /**
  12293. * Sets the current depth function to LEQUAL
  12294. */
  12295. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12296. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12297. };
  12298. /**
  12299. * Gets a boolean indicating if stencil buffer is enabled
  12300. * @returns the current stencil buffer state
  12301. */
  12302. Engine.prototype.getStencilBuffer = function () {
  12303. return this._stencilState.stencilTest;
  12304. };
  12305. /**
  12306. * Enable or disable the stencil buffer
  12307. * @param enable defines if the stencil buffer must be enabled or disabled
  12308. */
  12309. Engine.prototype.setStencilBuffer = function (enable) {
  12310. this._stencilState.stencilTest = enable;
  12311. };
  12312. /**
  12313. * Gets the current stencil mask
  12314. * @returns a number defining the new stencil mask to use
  12315. */
  12316. Engine.prototype.getStencilMask = function () {
  12317. return this._stencilState.stencilMask;
  12318. };
  12319. /**
  12320. * Sets the current stencil mask
  12321. * @param mask defines the new stencil mask to use
  12322. */
  12323. Engine.prototype.setStencilMask = function (mask) {
  12324. this._stencilState.stencilMask = mask;
  12325. };
  12326. /**
  12327. * Gets the current stencil function
  12328. * @returns a number defining the stencil function to use
  12329. */
  12330. Engine.prototype.getStencilFunction = function () {
  12331. return this._stencilState.stencilFunc;
  12332. };
  12333. /**
  12334. * Gets the current stencil reference value
  12335. * @returns a number defining the stencil reference value to use
  12336. */
  12337. Engine.prototype.getStencilFunctionReference = function () {
  12338. return this._stencilState.stencilFuncRef;
  12339. };
  12340. /**
  12341. * Gets the current stencil mask
  12342. * @returns a number defining the stencil mask to use
  12343. */
  12344. Engine.prototype.getStencilFunctionMask = function () {
  12345. return this._stencilState.stencilFuncMask;
  12346. };
  12347. /**
  12348. * Sets the current stencil function
  12349. * @param stencilFunc defines the new stencil function to use
  12350. */
  12351. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12352. this._stencilState.stencilFunc = stencilFunc;
  12353. };
  12354. /**
  12355. * Sets the current stencil reference
  12356. * @param reference defines the new stencil reference to use
  12357. */
  12358. Engine.prototype.setStencilFunctionReference = function (reference) {
  12359. this._stencilState.stencilFuncRef = reference;
  12360. };
  12361. /**
  12362. * Sets the current stencil mask
  12363. * @param mask defines the new stencil mask to use
  12364. */
  12365. Engine.prototype.setStencilFunctionMask = function (mask) {
  12366. this._stencilState.stencilFuncMask = mask;
  12367. };
  12368. /**
  12369. * Gets the current stencil operation when stencil fails
  12370. * @returns a number defining stencil operation to use when stencil fails
  12371. */
  12372. Engine.prototype.getStencilOperationFail = function () {
  12373. return this._stencilState.stencilOpStencilFail;
  12374. };
  12375. /**
  12376. * Gets the current stencil operation when depth fails
  12377. * @returns a number defining stencil operation to use when depth fails
  12378. */
  12379. Engine.prototype.getStencilOperationDepthFail = function () {
  12380. return this._stencilState.stencilOpDepthFail;
  12381. };
  12382. /**
  12383. * Gets the current stencil operation when stencil passes
  12384. * @returns a number defining stencil operation to use when stencil passes
  12385. */
  12386. Engine.prototype.getStencilOperationPass = function () {
  12387. return this._stencilState.stencilOpStencilDepthPass;
  12388. };
  12389. /**
  12390. * Sets the stencil operation to use when stencil fails
  12391. * @param operation defines the stencil operation to use when stencil fails
  12392. */
  12393. Engine.prototype.setStencilOperationFail = function (operation) {
  12394. this._stencilState.stencilOpStencilFail = operation;
  12395. };
  12396. /**
  12397. * Sets the stencil operation to use when depth fails
  12398. * @param operation defines the stencil operation to use when depth fails
  12399. */
  12400. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12401. this._stencilState.stencilOpDepthFail = operation;
  12402. };
  12403. /**
  12404. * Sets the stencil operation to use when stencil passes
  12405. * @param operation defines the stencil operation to use when stencil passes
  12406. */
  12407. Engine.prototype.setStencilOperationPass = function (operation) {
  12408. this._stencilState.stencilOpStencilDepthPass = operation;
  12409. };
  12410. /**
  12411. * Sets a boolean indicating if the dithering state is enabled or disabled
  12412. * @param value defines the dithering state
  12413. */
  12414. Engine.prototype.setDitheringState = function (value) {
  12415. if (value) {
  12416. this._gl.enable(this._gl.DITHER);
  12417. }
  12418. else {
  12419. this._gl.disable(this._gl.DITHER);
  12420. }
  12421. };
  12422. /**
  12423. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12424. * @param value defines the rasterizer state
  12425. */
  12426. Engine.prototype.setRasterizerState = function (value) {
  12427. if (value) {
  12428. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12429. }
  12430. else {
  12431. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12432. }
  12433. };
  12434. /**
  12435. * stop executing a render loop function and remove it from the execution array
  12436. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12437. */
  12438. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12439. if (!renderFunction) {
  12440. this._activeRenderLoops = [];
  12441. return;
  12442. }
  12443. var index = this._activeRenderLoops.indexOf(renderFunction);
  12444. if (index >= 0) {
  12445. this._activeRenderLoops.splice(index, 1);
  12446. }
  12447. };
  12448. /** @hidden */
  12449. Engine.prototype._renderLoop = function () {
  12450. if (!this._contextWasLost) {
  12451. var shouldRender = true;
  12452. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12453. shouldRender = false;
  12454. }
  12455. if (shouldRender) {
  12456. // Start new frame
  12457. this.beginFrame();
  12458. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12459. var renderFunction = this._activeRenderLoops[index];
  12460. renderFunction();
  12461. }
  12462. // Present
  12463. this.endFrame();
  12464. }
  12465. }
  12466. if (this._activeRenderLoops.length > 0) {
  12467. // Register new frame
  12468. var requester = null;
  12469. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12470. requester = this._vrDisplay;
  12471. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12472. }
  12473. else {
  12474. this._renderingQueueLaunched = false;
  12475. }
  12476. };
  12477. /**
  12478. * Register and execute a render loop. The engine can have more than one render function
  12479. * @param renderFunction defines the function to continuously execute
  12480. */
  12481. Engine.prototype.runRenderLoop = function (renderFunction) {
  12482. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12483. return;
  12484. }
  12485. this._activeRenderLoops.push(renderFunction);
  12486. if (!this._renderingQueueLaunched) {
  12487. this._renderingQueueLaunched = true;
  12488. this._bindedRenderFunction = this._renderLoop.bind(this);
  12489. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12490. }
  12491. };
  12492. /**
  12493. * Toggle full screen mode
  12494. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12495. * @param options defines an option object to be sent to the requestFullscreen function
  12496. */
  12497. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12498. if (this.isFullscreen) {
  12499. BABYLON.Tools.ExitFullscreen();
  12500. }
  12501. else {
  12502. this._pointerLockRequested = requestPointerLock;
  12503. if (this._renderingCanvas) {
  12504. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12505. }
  12506. }
  12507. };
  12508. /**
  12509. * Clear the current render buffer or the current render target (if any is set up)
  12510. * @param color defines the color to use
  12511. * @param backBuffer defines if the back buffer must be cleared
  12512. * @param depth defines if the depth buffer must be cleared
  12513. * @param stencil defines if the stencil buffer must be cleared
  12514. */
  12515. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12516. if (stencil === void 0) { stencil = false; }
  12517. this.applyStates();
  12518. var mode = 0;
  12519. if (backBuffer && color) {
  12520. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12521. mode |= this._gl.COLOR_BUFFER_BIT;
  12522. }
  12523. if (depth) {
  12524. this._gl.clearDepth(1.0);
  12525. mode |= this._gl.DEPTH_BUFFER_BIT;
  12526. }
  12527. if (stencil) {
  12528. this._gl.clearStencil(0);
  12529. mode |= this._gl.STENCIL_BUFFER_BIT;
  12530. }
  12531. this._gl.clear(mode);
  12532. };
  12533. /**
  12534. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12535. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12536. * @param y defines the y-coordinate of the corner of the clear rectangle
  12537. * @param width defines the width of the clear rectangle
  12538. * @param height defines the height of the clear rectangle
  12539. * @param clearColor defines the clear color
  12540. */
  12541. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12542. var gl = this._gl;
  12543. // Save state
  12544. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12545. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12546. // Change state
  12547. gl.enable(gl.SCISSOR_TEST);
  12548. gl.scissor(x, y, width, height);
  12549. // Clear
  12550. this.clear(clearColor, true, true, true);
  12551. // Restore state
  12552. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12553. if (curScissor === true) {
  12554. gl.enable(gl.SCISSOR_TEST);
  12555. }
  12556. else {
  12557. gl.disable(gl.SCISSOR_TEST);
  12558. }
  12559. };
  12560. /** @hidden */
  12561. Engine.prototype._viewport = function (x, y, width, height) {
  12562. if (x !== this._viewportCached.x ||
  12563. y !== this._viewportCached.y ||
  12564. width !== this._viewportCached.z ||
  12565. height !== this._viewportCached.w) {
  12566. this._viewportCached.x = x;
  12567. this._viewportCached.y = y;
  12568. this._viewportCached.z = width;
  12569. this._viewportCached.w = height;
  12570. this._gl.viewport(x, y, width, height);
  12571. }
  12572. };
  12573. /**
  12574. * Set the WebGL's viewport
  12575. * @param viewport defines the viewport element to be used
  12576. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12577. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12578. */
  12579. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12580. var width = requiredWidth || this.getRenderWidth();
  12581. var height = requiredHeight || this.getRenderHeight();
  12582. var x = viewport.x || 0;
  12583. var y = viewport.y || 0;
  12584. this._cachedViewport = viewport;
  12585. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12586. };
  12587. /**
  12588. * Directly set the WebGL Viewport
  12589. * @param x defines the x coordinate of the viewport (in screen space)
  12590. * @param y defines the y coordinate of the viewport (in screen space)
  12591. * @param width defines the width of the viewport (in screen space)
  12592. * @param height defines the height of the viewport (in screen space)
  12593. * @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
  12594. */
  12595. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12596. var currentViewport = this._cachedViewport;
  12597. this._cachedViewport = null;
  12598. this._viewport(x, y, width, height);
  12599. return currentViewport;
  12600. };
  12601. /**
  12602. * Begin a new frame
  12603. */
  12604. Engine.prototype.beginFrame = function () {
  12605. this.onBeginFrameObservable.notifyObservers(this);
  12606. this._measureFps();
  12607. };
  12608. /**
  12609. * Enf the current frame
  12610. */
  12611. Engine.prototype.endFrame = function () {
  12612. // Force a flush in case we are using a bad OS.
  12613. if (this._badOS) {
  12614. this.flushFramebuffer();
  12615. }
  12616. // Submit frame to the vr device, if enabled
  12617. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12618. // TODO: We should only submit the frame if we read frameData successfully.
  12619. this._vrDisplay.submitFrame();
  12620. }
  12621. this.onEndFrameObservable.notifyObservers(this);
  12622. };
  12623. /**
  12624. * Resize the view according to the canvas' size
  12625. */
  12626. Engine.prototype.resize = function () {
  12627. // We're not resizing the size of the canvas while in VR mode & presenting
  12628. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12629. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12630. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12631. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12632. }
  12633. };
  12634. /**
  12635. * Force a specific size of the canvas
  12636. * @param width defines the new canvas' width
  12637. * @param height defines the new canvas' height
  12638. */
  12639. Engine.prototype.setSize = function (width, height) {
  12640. if (!this._renderingCanvas) {
  12641. return;
  12642. }
  12643. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12644. return;
  12645. }
  12646. this._renderingCanvas.width = width;
  12647. this._renderingCanvas.height = height;
  12648. for (var index = 0; index < this.scenes.length; index++) {
  12649. var scene = this.scenes[index];
  12650. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12651. var cam = scene.cameras[camIndex];
  12652. cam._currentRenderId = 0;
  12653. }
  12654. }
  12655. if (this.onResizeObservable.hasObservers) {
  12656. this.onResizeObservable.notifyObservers(this);
  12657. }
  12658. };
  12659. // WebVR functions
  12660. /**
  12661. * Gets a boolean indicating if a webVR device was detected
  12662. * @returns true if a webVR device was detected
  12663. */
  12664. Engine.prototype.isVRDevicePresent = function () {
  12665. return !!this._vrDisplay;
  12666. };
  12667. /**
  12668. * Gets the current webVR device
  12669. * @returns the current webVR device (or null)
  12670. */
  12671. Engine.prototype.getVRDevice = function () {
  12672. return this._vrDisplay;
  12673. };
  12674. /**
  12675. * Initializes a webVR display and starts listening to display change events
  12676. * The onVRDisplayChangedObservable will be notified upon these changes
  12677. * @returns The onVRDisplayChangedObservable
  12678. */
  12679. Engine.prototype.initWebVR = function () {
  12680. this.initWebVRAsync();
  12681. return this.onVRDisplayChangedObservable;
  12682. };
  12683. /**
  12684. * Initializes a webVR display and starts listening to display change events
  12685. * The onVRDisplayChangedObservable will be notified upon these changes
  12686. * @returns A promise containing a VRDisplay and if vr is supported
  12687. */
  12688. Engine.prototype.initWebVRAsync = function () {
  12689. var _this = this;
  12690. var notifyObservers = function () {
  12691. var eventArgs = {
  12692. vrDisplay: _this._vrDisplay,
  12693. vrSupported: _this._vrSupported
  12694. };
  12695. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12696. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12697. };
  12698. if (!this._onVrDisplayConnect) {
  12699. this._onVrDisplayConnect = function (event) {
  12700. _this._vrDisplay = event.display;
  12701. notifyObservers();
  12702. };
  12703. this._onVrDisplayDisconnect = function () {
  12704. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12705. _this._vrDisplay = undefined;
  12706. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12707. notifyObservers();
  12708. };
  12709. this._onVrDisplayPresentChange = function () {
  12710. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12711. };
  12712. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12713. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12714. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12715. }
  12716. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12717. this._webVRInitPromise.then(notifyObservers);
  12718. return this._webVRInitPromise;
  12719. };
  12720. /**
  12721. * Call this function to switch to webVR mode
  12722. * Will do nothing if webVR is not supported or if there is no webVR device
  12723. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12724. */
  12725. Engine.prototype.enableVR = function () {
  12726. var _this = this;
  12727. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12728. var onResolved = function () {
  12729. _this.onVRRequestPresentComplete.notifyObservers(true);
  12730. _this._onVRFullScreenTriggered();
  12731. };
  12732. var onRejected = function () {
  12733. _this.onVRRequestPresentComplete.notifyObservers(false);
  12734. };
  12735. this.onVRRequestPresentStart.notifyObservers(this);
  12736. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12737. }
  12738. };
  12739. /**
  12740. * Call this function to leave webVR mode
  12741. * Will do nothing if webVR is not supported or if there is no webVR device
  12742. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12743. */
  12744. Engine.prototype.disableVR = function () {
  12745. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12746. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12747. }
  12748. };
  12749. Engine.prototype._getVRDisplaysAsync = function () {
  12750. var _this = this;
  12751. return new Promise(function (res, rej) {
  12752. if (navigator.getVRDisplays) {
  12753. navigator.getVRDisplays().then(function (devices) {
  12754. _this._vrSupported = true;
  12755. // note that devices may actually be an empty array. This is fine;
  12756. // we expect this._vrDisplay to be undefined in this case.
  12757. _this._vrDisplay = devices[0];
  12758. res({
  12759. vrDisplay: _this._vrDisplay,
  12760. vrSupported: _this._vrSupported
  12761. });
  12762. });
  12763. }
  12764. else {
  12765. _this._vrDisplay = undefined;
  12766. _this._vrSupported = false;
  12767. res({
  12768. vrDisplay: _this._vrDisplay,
  12769. vrSupported: _this._vrSupported
  12770. });
  12771. }
  12772. });
  12773. };
  12774. /**
  12775. * Binds the frame buffer to the specified texture.
  12776. * @param texture The texture to render to or null for the default canvas
  12777. * @param faceIndex The face of the texture to render to in case of cube texture
  12778. * @param requiredWidth The width of the target to render to
  12779. * @param requiredHeight The height of the target to render to
  12780. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12781. * @param depthStencilTexture The depth stencil texture to use to render
  12782. * @param lodLevel defines le lod level to bind to the frame buffer
  12783. */
  12784. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12785. if (lodLevel === void 0) { lodLevel = 0; }
  12786. if (this._currentRenderTarget) {
  12787. this.unBindFramebuffer(this._currentRenderTarget);
  12788. }
  12789. this._currentRenderTarget = texture;
  12790. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12791. var gl = this._gl;
  12792. if (texture.isCube) {
  12793. if (faceIndex === undefined) {
  12794. faceIndex = 0;
  12795. }
  12796. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12797. if (depthStencilTexture) {
  12798. if (depthStencilTexture._generateStencilBuffer) {
  12799. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12800. }
  12801. else {
  12802. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12803. }
  12804. }
  12805. }
  12806. if (this._cachedViewport && !forceFullscreenViewport) {
  12807. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12808. }
  12809. else {
  12810. if (!requiredWidth) {
  12811. requiredWidth = texture.width;
  12812. if (lodLevel) {
  12813. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12814. }
  12815. }
  12816. if (!requiredHeight) {
  12817. requiredHeight = texture.height;
  12818. if (lodLevel) {
  12819. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12820. }
  12821. }
  12822. this._viewport(0, 0, requiredWidth, requiredHeight);
  12823. }
  12824. this.wipeCaches();
  12825. };
  12826. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12827. if (this._currentFramebuffer !== framebuffer) {
  12828. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12829. this._currentFramebuffer = framebuffer;
  12830. }
  12831. };
  12832. /**
  12833. * Unbind the current render target texture from the webGL context
  12834. * @param texture defines the render target texture to unbind
  12835. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12836. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12837. */
  12838. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12839. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12840. this._currentRenderTarget = null;
  12841. // If MSAA, we need to bitblt back to main texture
  12842. var gl = this._gl;
  12843. if (texture._MSAAFramebuffer) {
  12844. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12845. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12846. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12847. }
  12848. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12849. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12850. gl.generateMipmap(gl.TEXTURE_2D);
  12851. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12852. }
  12853. if (onBeforeUnbind) {
  12854. if (texture._MSAAFramebuffer) {
  12855. // Bind the correct framebuffer
  12856. this.bindUnboundFramebuffer(texture._framebuffer);
  12857. }
  12858. onBeforeUnbind();
  12859. }
  12860. this.bindUnboundFramebuffer(null);
  12861. };
  12862. /**
  12863. * Unbind a list of render target textures from the webGL context
  12864. * This is used only when drawBuffer extension or webGL2 are active
  12865. * @param textures defines the render target textures to unbind
  12866. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12867. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12868. */
  12869. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12870. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12871. this._currentRenderTarget = null;
  12872. // If MSAA, we need to bitblt back to main texture
  12873. var gl = this._gl;
  12874. if (textures[0]._MSAAFramebuffer) {
  12875. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12876. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12877. var attachments = textures[0]._attachments;
  12878. if (!attachments) {
  12879. attachments = new Array(textures.length);
  12880. textures[0]._attachments = attachments;
  12881. }
  12882. for (var i = 0; i < textures.length; i++) {
  12883. var texture = textures[i];
  12884. for (var j = 0; j < attachments.length; j++) {
  12885. attachments[j] = gl.NONE;
  12886. }
  12887. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12888. gl.readBuffer(attachments[i]);
  12889. gl.drawBuffers(attachments);
  12890. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12891. }
  12892. for (var i = 0; i < attachments.length; i++) {
  12893. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12894. }
  12895. gl.drawBuffers(attachments);
  12896. }
  12897. for (var i = 0; i < textures.length; i++) {
  12898. var texture = textures[i];
  12899. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12900. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12901. gl.generateMipmap(gl.TEXTURE_2D);
  12902. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12903. }
  12904. }
  12905. if (onBeforeUnbind) {
  12906. if (textures[0]._MSAAFramebuffer) {
  12907. // Bind the correct framebuffer
  12908. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12909. }
  12910. onBeforeUnbind();
  12911. }
  12912. this.bindUnboundFramebuffer(null);
  12913. };
  12914. /**
  12915. * Force the mipmap generation for the given render target texture
  12916. * @param texture defines the render target texture to use
  12917. */
  12918. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12919. if (texture.generateMipMaps) {
  12920. var gl = this._gl;
  12921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12922. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12923. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12924. }
  12925. };
  12926. /**
  12927. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12928. */
  12929. Engine.prototype.flushFramebuffer = function () {
  12930. this._gl.flush();
  12931. };
  12932. /**
  12933. * Unbind the current render target and bind the default framebuffer
  12934. */
  12935. Engine.prototype.restoreDefaultFramebuffer = function () {
  12936. if (this._currentRenderTarget) {
  12937. this.unBindFramebuffer(this._currentRenderTarget);
  12938. }
  12939. else {
  12940. this.bindUnboundFramebuffer(null);
  12941. }
  12942. if (this._cachedViewport) {
  12943. this.setViewport(this._cachedViewport);
  12944. }
  12945. this.wipeCaches();
  12946. };
  12947. // UBOs
  12948. /**
  12949. * Create an uniform buffer
  12950. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12951. * @param elements defines the content of the uniform buffer
  12952. * @returns the webGL uniform buffer
  12953. */
  12954. Engine.prototype.createUniformBuffer = function (elements) {
  12955. var ubo = this._gl.createBuffer();
  12956. if (!ubo) {
  12957. throw new Error("Unable to create uniform buffer");
  12958. }
  12959. this.bindUniformBuffer(ubo);
  12960. if (elements instanceof Float32Array) {
  12961. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12962. }
  12963. else {
  12964. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12965. }
  12966. this.bindUniformBuffer(null);
  12967. ubo.references = 1;
  12968. return ubo;
  12969. };
  12970. /**
  12971. * Create a dynamic uniform buffer
  12972. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12973. * @param elements defines the content of the uniform buffer
  12974. * @returns the webGL uniform buffer
  12975. */
  12976. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12977. var ubo = this._gl.createBuffer();
  12978. if (!ubo) {
  12979. throw new Error("Unable to create dynamic uniform buffer");
  12980. }
  12981. this.bindUniformBuffer(ubo);
  12982. if (elements instanceof Float32Array) {
  12983. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12984. }
  12985. else {
  12986. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12987. }
  12988. this.bindUniformBuffer(null);
  12989. ubo.references = 1;
  12990. return ubo;
  12991. };
  12992. /**
  12993. * Update an existing uniform buffer
  12994. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12995. * @param uniformBuffer defines the target uniform buffer
  12996. * @param elements defines the content to update
  12997. * @param offset defines the offset in the uniform buffer where update should start
  12998. * @param count defines the size of the data to update
  12999. */
  13000. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13001. this.bindUniformBuffer(uniformBuffer);
  13002. if (offset === undefined) {
  13003. offset = 0;
  13004. }
  13005. if (count === undefined) {
  13006. if (elements instanceof Float32Array) {
  13007. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13008. }
  13009. else {
  13010. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13011. }
  13012. }
  13013. else {
  13014. if (elements instanceof Float32Array) {
  13015. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13016. }
  13017. else {
  13018. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13019. }
  13020. }
  13021. this.bindUniformBuffer(null);
  13022. };
  13023. // VBOs
  13024. Engine.prototype._resetVertexBufferBinding = function () {
  13025. this.bindArrayBuffer(null);
  13026. this._cachedVertexBuffers = null;
  13027. };
  13028. /**
  13029. * Creates a vertex buffer
  13030. * @param data the data for the vertex buffer
  13031. * @returns the new WebGL static buffer
  13032. */
  13033. Engine.prototype.createVertexBuffer = function (data) {
  13034. var vbo = this._gl.createBuffer();
  13035. if (!vbo) {
  13036. throw new Error("Unable to create vertex buffer");
  13037. }
  13038. this.bindArrayBuffer(vbo);
  13039. if (data instanceof Array) {
  13040. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13041. }
  13042. else {
  13043. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13044. }
  13045. this._resetVertexBufferBinding();
  13046. vbo.references = 1;
  13047. return vbo;
  13048. };
  13049. /**
  13050. * Creates a dynamic vertex buffer
  13051. * @param data the data for the dynamic vertex buffer
  13052. * @returns the new WebGL dynamic buffer
  13053. */
  13054. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13055. var vbo = this._gl.createBuffer();
  13056. if (!vbo) {
  13057. throw new Error("Unable to create dynamic vertex buffer");
  13058. }
  13059. this.bindArrayBuffer(vbo);
  13060. if (data instanceof Array) {
  13061. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13062. }
  13063. else {
  13064. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13065. }
  13066. this._resetVertexBufferBinding();
  13067. vbo.references = 1;
  13068. return vbo;
  13069. };
  13070. /**
  13071. * Update a dynamic index buffer
  13072. * @param indexBuffer defines the target index buffer
  13073. * @param indices defines the data to update
  13074. * @param offset defines the offset in the target index buffer where update should start
  13075. */
  13076. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13077. if (offset === void 0) { offset = 0; }
  13078. // Force cache update
  13079. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13080. this.bindIndexBuffer(indexBuffer);
  13081. var arrayBuffer;
  13082. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13083. arrayBuffer = indices;
  13084. }
  13085. else {
  13086. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13087. }
  13088. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13089. this._resetIndexBufferBinding();
  13090. };
  13091. /**
  13092. * Updates a dynamic vertex buffer.
  13093. * @param vertexBuffer the vertex buffer to update
  13094. * @param data the data used to update the vertex buffer
  13095. * @param byteOffset the byte offset of the data
  13096. * @param byteLength the byte length of the data
  13097. */
  13098. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13099. this.bindArrayBuffer(vertexBuffer);
  13100. if (byteOffset === undefined) {
  13101. byteOffset = 0;
  13102. }
  13103. if (byteLength === undefined) {
  13104. if (data instanceof Array) {
  13105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13106. }
  13107. else {
  13108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13109. }
  13110. }
  13111. else {
  13112. if (data instanceof Array) {
  13113. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13114. }
  13115. else {
  13116. if (data instanceof ArrayBuffer) {
  13117. data = new Uint8Array(data, byteOffset, byteLength);
  13118. }
  13119. else {
  13120. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13121. }
  13122. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13123. }
  13124. }
  13125. this._resetVertexBufferBinding();
  13126. };
  13127. Engine.prototype._resetIndexBufferBinding = function () {
  13128. this.bindIndexBuffer(null);
  13129. this._cachedIndexBuffer = null;
  13130. };
  13131. /**
  13132. * Creates a new index buffer
  13133. * @param indices defines the content of the index buffer
  13134. * @param updatable defines if the index buffer must be updatable
  13135. * @returns a new webGL buffer
  13136. */
  13137. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13138. var vbo = this._gl.createBuffer();
  13139. if (!vbo) {
  13140. throw new Error("Unable to create index buffer");
  13141. }
  13142. this.bindIndexBuffer(vbo);
  13143. // Check for 32 bits indices
  13144. var arrayBuffer;
  13145. var need32Bits = false;
  13146. if (indices instanceof Uint16Array) {
  13147. arrayBuffer = indices;
  13148. }
  13149. else {
  13150. //check 32 bit support
  13151. if (this._caps.uintIndices) {
  13152. if (indices instanceof Uint32Array) {
  13153. arrayBuffer = indices;
  13154. need32Bits = true;
  13155. }
  13156. else {
  13157. //number[] or Int32Array, check if 32 bit is necessary
  13158. for (var index = 0; index < indices.length; index++) {
  13159. if (indices[index] > 65535) {
  13160. need32Bits = true;
  13161. break;
  13162. }
  13163. }
  13164. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13165. }
  13166. }
  13167. else {
  13168. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13169. arrayBuffer = new Uint16Array(indices);
  13170. }
  13171. }
  13172. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13173. this._resetIndexBufferBinding();
  13174. vbo.references = 1;
  13175. vbo.is32Bits = need32Bits;
  13176. return vbo;
  13177. };
  13178. /**
  13179. * Bind a webGL buffer to the webGL context
  13180. * @param buffer defines the buffer to bind
  13181. */
  13182. Engine.prototype.bindArrayBuffer = function (buffer) {
  13183. if (!this._vaoRecordInProgress) {
  13184. this._unbindVertexArrayObject();
  13185. }
  13186. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13187. };
  13188. /**
  13189. * Bind an uniform buffer to the current webGL context
  13190. * @param buffer defines the buffer to bind
  13191. */
  13192. Engine.prototype.bindUniformBuffer = function (buffer) {
  13193. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13194. };
  13195. /**
  13196. * Bind a buffer to the current webGL context at a given location
  13197. * @param buffer defines the buffer to bind
  13198. * @param location defines the index where to bind the buffer
  13199. */
  13200. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13201. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13202. };
  13203. /**
  13204. * Bind a specific block at a given index in a specific shader program
  13205. * @param shaderProgram defines the shader program
  13206. * @param blockName defines the block name
  13207. * @param index defines the index where to bind the block
  13208. */
  13209. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13210. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13211. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13212. };
  13213. ;
  13214. Engine.prototype.bindIndexBuffer = function (buffer) {
  13215. if (!this._vaoRecordInProgress) {
  13216. this._unbindVertexArrayObject();
  13217. }
  13218. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13219. };
  13220. Engine.prototype.bindBuffer = function (buffer, target) {
  13221. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13222. this._gl.bindBuffer(target, buffer);
  13223. this._currentBoundBuffer[target] = buffer;
  13224. }
  13225. };
  13226. /**
  13227. * update the bound buffer with the given data
  13228. * @param data defines the data to update
  13229. */
  13230. Engine.prototype.updateArrayBuffer = function (data) {
  13231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13232. };
  13233. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13234. var pointer = this._currentBufferPointers[indx];
  13235. var changed = false;
  13236. if (!pointer.active) {
  13237. changed = true;
  13238. pointer.active = true;
  13239. pointer.index = indx;
  13240. pointer.size = size;
  13241. pointer.type = type;
  13242. pointer.normalized = normalized;
  13243. pointer.stride = stride;
  13244. pointer.offset = offset;
  13245. pointer.buffer = buffer;
  13246. }
  13247. else {
  13248. if (pointer.buffer !== buffer) {
  13249. pointer.buffer = buffer;
  13250. changed = true;
  13251. }
  13252. if (pointer.size !== size) {
  13253. pointer.size = size;
  13254. changed = true;
  13255. }
  13256. if (pointer.type !== type) {
  13257. pointer.type = type;
  13258. changed = true;
  13259. }
  13260. if (pointer.normalized !== normalized) {
  13261. pointer.normalized = normalized;
  13262. changed = true;
  13263. }
  13264. if (pointer.stride !== stride) {
  13265. pointer.stride = stride;
  13266. changed = true;
  13267. }
  13268. if (pointer.offset !== offset) {
  13269. pointer.offset = offset;
  13270. changed = true;
  13271. }
  13272. }
  13273. if (changed || this._vaoRecordInProgress) {
  13274. this.bindArrayBuffer(buffer);
  13275. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13276. }
  13277. };
  13278. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13279. if (indexBuffer == null) {
  13280. return;
  13281. }
  13282. if (this._cachedIndexBuffer !== indexBuffer) {
  13283. this._cachedIndexBuffer = indexBuffer;
  13284. this.bindIndexBuffer(indexBuffer);
  13285. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13286. }
  13287. };
  13288. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13289. var attributes = effect.getAttributesNames();
  13290. if (!this._vaoRecordInProgress) {
  13291. this._unbindVertexArrayObject();
  13292. }
  13293. this.unbindAllAttributes();
  13294. for (var index = 0; index < attributes.length; index++) {
  13295. var order = effect.getAttributeLocation(index);
  13296. if (order >= 0) {
  13297. var vertexBuffer = vertexBuffers[attributes[index]];
  13298. if (!vertexBuffer) {
  13299. continue;
  13300. }
  13301. this._gl.enableVertexAttribArray(order);
  13302. if (!this._vaoRecordInProgress) {
  13303. this._vertexAttribArraysEnabled[order] = true;
  13304. }
  13305. var buffer = vertexBuffer.getBuffer();
  13306. if (buffer) {
  13307. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13308. if (vertexBuffer.getIsInstanced()) {
  13309. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13310. if (!this._vaoRecordInProgress) {
  13311. this._currentInstanceLocations.push(order);
  13312. this._currentInstanceBuffers.push(buffer);
  13313. }
  13314. }
  13315. }
  13316. }
  13317. }
  13318. };
  13319. /**
  13320. * Records a vertex array object
  13321. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13322. * @param vertexBuffers defines the list of vertex buffers to store
  13323. * @param indexBuffer defines the index buffer to store
  13324. * @param effect defines the effect to store
  13325. * @returns the new vertex array object
  13326. */
  13327. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13328. var vao = this._gl.createVertexArray();
  13329. this._vaoRecordInProgress = true;
  13330. this._gl.bindVertexArray(vao);
  13331. this._mustWipeVertexAttributes = true;
  13332. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13333. this.bindIndexBuffer(indexBuffer);
  13334. this._vaoRecordInProgress = false;
  13335. this._gl.bindVertexArray(null);
  13336. return vao;
  13337. };
  13338. /**
  13339. * Bind a specific vertex array object
  13340. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13341. * @param vertexArrayObject defines the vertex array object to bind
  13342. * @param indexBuffer defines the index buffer to bind
  13343. */
  13344. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13345. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13346. this._cachedVertexArrayObject = vertexArrayObject;
  13347. this._gl.bindVertexArray(vertexArrayObject);
  13348. this._cachedVertexBuffers = null;
  13349. this._cachedIndexBuffer = null;
  13350. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13351. this._mustWipeVertexAttributes = true;
  13352. }
  13353. };
  13354. /**
  13355. * Bind webGl buffers directly to the webGL context
  13356. * @param vertexBuffer defines the vertex buffer to bind
  13357. * @param indexBuffer defines the index buffer to bind
  13358. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13359. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13360. * @param effect defines the effect associated with the vertex buffer
  13361. */
  13362. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13363. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13364. this._cachedVertexBuffers = vertexBuffer;
  13365. this._cachedEffectForVertexBuffers = effect;
  13366. var attributesCount = effect.getAttributesCount();
  13367. this._unbindVertexArrayObject();
  13368. this.unbindAllAttributes();
  13369. var offset = 0;
  13370. for (var index = 0; index < attributesCount; index++) {
  13371. if (index < vertexDeclaration.length) {
  13372. var order = effect.getAttributeLocation(index);
  13373. if (order >= 0) {
  13374. this._gl.enableVertexAttribArray(order);
  13375. this._vertexAttribArraysEnabled[order] = true;
  13376. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13377. }
  13378. offset += vertexDeclaration[index] * 4;
  13379. }
  13380. }
  13381. }
  13382. this._bindIndexBufferWithCache(indexBuffer);
  13383. };
  13384. Engine.prototype._unbindVertexArrayObject = function () {
  13385. if (!this._cachedVertexArrayObject) {
  13386. return;
  13387. }
  13388. this._cachedVertexArrayObject = null;
  13389. this._gl.bindVertexArray(null);
  13390. };
  13391. /**
  13392. * Bind a list of vertex buffers to the webGL context
  13393. * @param vertexBuffers defines the list of vertex buffers to bind
  13394. * @param indexBuffer defines the index buffer to bind
  13395. * @param effect defines the effect associated with the vertex buffers
  13396. */
  13397. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13398. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13399. this._cachedVertexBuffers = vertexBuffers;
  13400. this._cachedEffectForVertexBuffers = effect;
  13401. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13402. }
  13403. this._bindIndexBufferWithCache(indexBuffer);
  13404. };
  13405. /**
  13406. * Unbind all instance attributes
  13407. */
  13408. Engine.prototype.unbindInstanceAttributes = function () {
  13409. var boundBuffer;
  13410. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13411. var instancesBuffer = this._currentInstanceBuffers[i];
  13412. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13413. boundBuffer = instancesBuffer;
  13414. this.bindArrayBuffer(instancesBuffer);
  13415. }
  13416. var offsetLocation = this._currentInstanceLocations[i];
  13417. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13418. }
  13419. this._currentInstanceBuffers.length = 0;
  13420. this._currentInstanceLocations.length = 0;
  13421. };
  13422. /**
  13423. * Release and free the memory of a vertex array object
  13424. * @param vao defines the vertex array object to delete
  13425. */
  13426. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13427. this._gl.deleteVertexArray(vao);
  13428. };
  13429. /** @hidden */
  13430. Engine.prototype._releaseBuffer = function (buffer) {
  13431. buffer.references--;
  13432. if (buffer.references === 0) {
  13433. this._gl.deleteBuffer(buffer);
  13434. return true;
  13435. }
  13436. return false;
  13437. };
  13438. /**
  13439. * Creates a webGL buffer to use with instanciation
  13440. * @param capacity defines the size of the buffer
  13441. * @returns the webGL buffer
  13442. */
  13443. Engine.prototype.createInstancesBuffer = function (capacity) {
  13444. var buffer = this._gl.createBuffer();
  13445. if (!buffer) {
  13446. throw new Error("Unable to create instance buffer");
  13447. }
  13448. buffer.capacity = capacity;
  13449. this.bindArrayBuffer(buffer);
  13450. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13451. return buffer;
  13452. };
  13453. /**
  13454. * Delete a webGL buffer used with instanciation
  13455. * @param buffer defines the webGL buffer to delete
  13456. */
  13457. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13458. this._gl.deleteBuffer(buffer);
  13459. };
  13460. /**
  13461. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13462. * @param instancesBuffer defines the webGL buffer to update and bind
  13463. * @param data defines the data to store in the buffer
  13464. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13465. */
  13466. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13467. this.bindArrayBuffer(instancesBuffer);
  13468. if (data) {
  13469. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13470. }
  13471. if (offsetLocations[0].index !== undefined) {
  13472. var stride = 0;
  13473. for (var i = 0; i < offsetLocations.length; i++) {
  13474. var ai = offsetLocations[i];
  13475. stride += ai.attributeSize * 4;
  13476. }
  13477. for (var i = 0; i < offsetLocations.length; i++) {
  13478. var ai = offsetLocations[i];
  13479. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13480. this._gl.enableVertexAttribArray(ai.index);
  13481. this._vertexAttribArraysEnabled[ai.index] = true;
  13482. }
  13483. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13484. this._gl.vertexAttribDivisor(ai.index, 1);
  13485. this._currentInstanceLocations.push(ai.index);
  13486. this._currentInstanceBuffers.push(instancesBuffer);
  13487. }
  13488. }
  13489. else {
  13490. for (var index = 0; index < 4; index++) {
  13491. var offsetLocation = offsetLocations[index];
  13492. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13493. this._gl.enableVertexAttribArray(offsetLocation);
  13494. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13495. }
  13496. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13497. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13498. this._currentInstanceLocations.push(offsetLocation);
  13499. this._currentInstanceBuffers.push(instancesBuffer);
  13500. }
  13501. }
  13502. };
  13503. /**
  13504. * Apply all cached states (depth, culling, stencil and alpha)
  13505. */
  13506. Engine.prototype.applyStates = function () {
  13507. this._depthCullingState.apply(this._gl);
  13508. this._stencilState.apply(this._gl);
  13509. this._alphaState.apply(this._gl);
  13510. };
  13511. /**
  13512. * Send a draw order
  13513. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13514. * @param indexStart defines the starting index
  13515. * @param indexCount defines the number of index to draw
  13516. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13517. */
  13518. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13519. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13520. };
  13521. /**
  13522. * Draw a list of points
  13523. * @param verticesStart defines the index of first vertex to draw
  13524. * @param verticesCount defines the count of vertices to draw
  13525. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13526. */
  13527. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13528. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13529. };
  13530. /**
  13531. * Draw a list of unindexed primitives
  13532. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13533. * @param verticesStart defines the index of first vertex to draw
  13534. * @param verticesCount defines the count of vertices to draw
  13535. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13536. */
  13537. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13538. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13539. };
  13540. /**
  13541. * Draw a list of indexed primitives
  13542. * @param fillMode defines the primitive to use
  13543. * @param indexStart defines the starting index
  13544. * @param indexCount defines the number of index to draw
  13545. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13546. */
  13547. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13548. // Apply states
  13549. this.applyStates();
  13550. this._drawCalls.addCount(1, false);
  13551. // Render
  13552. var drawMode = this._drawMode(fillMode);
  13553. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13554. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13555. if (instancesCount) {
  13556. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13557. }
  13558. else {
  13559. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13560. }
  13561. };
  13562. /**
  13563. * Draw a list of unindexed primitives
  13564. * @param fillMode defines the primitive to use
  13565. * @param verticesStart defines the index of first vertex to draw
  13566. * @param verticesCount defines the count of vertices to draw
  13567. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13568. */
  13569. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13570. // Apply states
  13571. this.applyStates();
  13572. this._drawCalls.addCount(1, false);
  13573. var drawMode = this._drawMode(fillMode);
  13574. if (instancesCount) {
  13575. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13576. }
  13577. else {
  13578. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13579. }
  13580. };
  13581. Engine.prototype._drawMode = function (fillMode) {
  13582. switch (fillMode) {
  13583. // Triangle views
  13584. case BABYLON.Material.TriangleFillMode:
  13585. return this._gl.TRIANGLES;
  13586. case BABYLON.Material.PointFillMode:
  13587. return this._gl.POINTS;
  13588. case BABYLON.Material.WireFrameFillMode:
  13589. return this._gl.LINES;
  13590. // Draw modes
  13591. case BABYLON.Material.PointListDrawMode:
  13592. return this._gl.POINTS;
  13593. case BABYLON.Material.LineListDrawMode:
  13594. return this._gl.LINES;
  13595. case BABYLON.Material.LineLoopDrawMode:
  13596. return this._gl.LINE_LOOP;
  13597. case BABYLON.Material.LineStripDrawMode:
  13598. return this._gl.LINE_STRIP;
  13599. case BABYLON.Material.TriangleStripDrawMode:
  13600. return this._gl.TRIANGLE_STRIP;
  13601. case BABYLON.Material.TriangleFanDrawMode:
  13602. return this._gl.TRIANGLE_FAN;
  13603. default:
  13604. return this._gl.TRIANGLES;
  13605. }
  13606. };
  13607. // Shaders
  13608. /** @hidden */
  13609. Engine.prototype._releaseEffect = function (effect) {
  13610. if (this._compiledEffects[effect._key]) {
  13611. delete this._compiledEffects[effect._key];
  13612. this._deleteProgram(effect.getProgram());
  13613. }
  13614. };
  13615. /** @hidden */
  13616. Engine.prototype._deleteProgram = function (program) {
  13617. if (program) {
  13618. program.__SPECTOR_rebuildProgram = null;
  13619. if (program.transformFeedback) {
  13620. this.deleteTransformFeedback(program.transformFeedback);
  13621. program.transformFeedback = null;
  13622. }
  13623. this._gl.deleteProgram(program);
  13624. }
  13625. };
  13626. /**
  13627. * Create a new effect (used to store vertex/fragment shaders)
  13628. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13629. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13630. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13631. * @param samplers defines an array of string used to represent textures
  13632. * @param defines defines the string containing the defines to use to compile the shaders
  13633. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13634. * @param onCompiled defines a function to call when the effect creation is successful
  13635. * @param onError defines a function to call when the effect creation has failed
  13636. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13637. * @returns the new Effect
  13638. */
  13639. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13640. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13641. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13642. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13643. if (this._compiledEffects[name]) {
  13644. var compiledEffect = this._compiledEffects[name];
  13645. if (onCompiled && compiledEffect.isReady()) {
  13646. onCompiled(compiledEffect);
  13647. }
  13648. return compiledEffect;
  13649. }
  13650. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13651. effect._key = name;
  13652. this._compiledEffects[name] = effect;
  13653. return effect;
  13654. };
  13655. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13656. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13657. };
  13658. ;
  13659. Engine.prototype._compileRawShader = function (source, type) {
  13660. var gl = this._gl;
  13661. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13662. gl.shaderSource(shader, source);
  13663. gl.compileShader(shader);
  13664. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13665. var log = gl.getShaderInfoLog(shader);
  13666. if (log) {
  13667. throw new Error(log);
  13668. }
  13669. }
  13670. if (!shader) {
  13671. throw new Error("Something went wrong while compile the shader.");
  13672. }
  13673. return shader;
  13674. };
  13675. ;
  13676. /**
  13677. * Directly creates a webGL program
  13678. * @param vertexCode defines the vertex shader code to use
  13679. * @param fragmentCode defines the fragment shader code to use
  13680. * @param context defines the webGL context to use (if not set, the current one will be used)
  13681. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13682. * @returns the new webGL program
  13683. */
  13684. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13685. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13686. context = context || this._gl;
  13687. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13688. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13689. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13690. };
  13691. /**
  13692. * Creates a webGL program
  13693. * @param vertexCode defines the vertex shader code to use
  13694. * @param fragmentCode defines the fragment shader code to use
  13695. * @param defines defines the string containing the defines to use to compile the shaders
  13696. * @param context defines the webGL context to use (if not set, the current one will be used)
  13697. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13698. * @returns the new webGL program
  13699. */
  13700. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13701. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13702. context = context || this._gl;
  13703. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13704. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13705. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13706. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13707. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13708. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13709. return program;
  13710. };
  13711. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13712. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13713. var shaderProgram = context.createProgram();
  13714. if (!shaderProgram) {
  13715. throw new Error("Unable to create program");
  13716. }
  13717. context.attachShader(shaderProgram, vertexShader);
  13718. context.attachShader(shaderProgram, fragmentShader);
  13719. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13720. var transformFeedback = this.createTransformFeedback();
  13721. this.bindTransformFeedback(transformFeedback);
  13722. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13723. shaderProgram.transformFeedback = transformFeedback;
  13724. }
  13725. context.linkProgram(shaderProgram);
  13726. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13727. this.bindTransformFeedback(null);
  13728. }
  13729. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13730. if (!linked) {
  13731. var error = context.getProgramInfoLog(shaderProgram);
  13732. if (error) {
  13733. throw new Error(error);
  13734. }
  13735. }
  13736. if (this.validateShaderPrograms) {
  13737. context.validateProgram(shaderProgram);
  13738. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13739. if (!validated) {
  13740. var error = context.getProgramInfoLog(shaderProgram);
  13741. if (error) {
  13742. throw new Error(error);
  13743. }
  13744. }
  13745. }
  13746. context.deleteShader(vertexShader);
  13747. context.deleteShader(fragmentShader);
  13748. return shaderProgram;
  13749. };
  13750. /**
  13751. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13752. * @param shaderProgram defines the webGL program to use
  13753. * @param uniformsNames defines the list of uniform names
  13754. * @returns an array of webGL uniform locations
  13755. */
  13756. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13757. var results = new Array();
  13758. for (var index = 0; index < uniformsNames.length; index++) {
  13759. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13760. }
  13761. return results;
  13762. };
  13763. /**
  13764. * Gets the lsit of active attributes for a given webGL program
  13765. * @param shaderProgram defines the webGL program to use
  13766. * @param attributesNames defines the list of attribute names to get
  13767. * @returns an array of indices indicating the offset of each attribute
  13768. */
  13769. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13770. var results = [];
  13771. for (var index = 0; index < attributesNames.length; index++) {
  13772. try {
  13773. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13774. }
  13775. catch (e) {
  13776. results.push(-1);
  13777. }
  13778. }
  13779. return results;
  13780. };
  13781. /**
  13782. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13783. * @param effect defines the effect to activate
  13784. */
  13785. Engine.prototype.enableEffect = function (effect) {
  13786. if (!effect || effect === this._currentEffect) {
  13787. return;
  13788. }
  13789. // Use program
  13790. this.bindSamplers(effect);
  13791. this._currentEffect = effect;
  13792. if (effect.onBind) {
  13793. effect.onBind(effect);
  13794. }
  13795. if (effect._onBindObservable) {
  13796. effect._onBindObservable.notifyObservers(effect);
  13797. }
  13798. };
  13799. /**
  13800. * Set the value of an uniform to an array of int32
  13801. * @param uniform defines the webGL uniform location where to store the value
  13802. * @param array defines the array of int32 to store
  13803. */
  13804. Engine.prototype.setIntArray = function (uniform, array) {
  13805. if (!uniform)
  13806. return;
  13807. this._gl.uniform1iv(uniform, array);
  13808. };
  13809. /**
  13810. * Set the value of an uniform to an array of int32 (stored as vec2)
  13811. * @param uniform defines the webGL uniform location where to store the value
  13812. * @param array defines the array of int32 to store
  13813. */
  13814. Engine.prototype.setIntArray2 = function (uniform, array) {
  13815. if (!uniform || array.length % 2 !== 0)
  13816. return;
  13817. this._gl.uniform2iv(uniform, array);
  13818. };
  13819. /**
  13820. * Set the value of an uniform to an array of int32 (stored as vec3)
  13821. * @param uniform defines the webGL uniform location where to store the value
  13822. * @param array defines the array of int32 to store
  13823. */
  13824. Engine.prototype.setIntArray3 = function (uniform, array) {
  13825. if (!uniform || array.length % 3 !== 0)
  13826. return;
  13827. this._gl.uniform3iv(uniform, array);
  13828. };
  13829. /**
  13830. * Set the value of an uniform to an array of int32 (stored as vec4)
  13831. * @param uniform defines the webGL uniform location where to store the value
  13832. * @param array defines the array of int32 to store
  13833. */
  13834. Engine.prototype.setIntArray4 = function (uniform, array) {
  13835. if (!uniform || array.length % 4 !== 0)
  13836. return;
  13837. this._gl.uniform4iv(uniform, array);
  13838. };
  13839. /**
  13840. * Set the value of an uniform to an array of float32
  13841. * @param uniform defines the webGL uniform location where to store the value
  13842. * @param array defines the array of float32 to store
  13843. */
  13844. Engine.prototype.setFloatArray = function (uniform, array) {
  13845. if (!uniform)
  13846. return;
  13847. this._gl.uniform1fv(uniform, array);
  13848. };
  13849. /**
  13850. * Set the value of an uniform to an array of float32 (stored as vec2)
  13851. * @param uniform defines the webGL uniform location where to store the value
  13852. * @param array defines the array of float32 to store
  13853. */
  13854. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13855. if (!uniform || array.length % 2 !== 0)
  13856. return;
  13857. this._gl.uniform2fv(uniform, array);
  13858. };
  13859. /**
  13860. * Set the value of an uniform to an array of float32 (stored as vec3)
  13861. * @param uniform defines the webGL uniform location where to store the value
  13862. * @param array defines the array of float32 to store
  13863. */
  13864. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13865. if (!uniform || array.length % 3 !== 0)
  13866. return;
  13867. this._gl.uniform3fv(uniform, array);
  13868. };
  13869. /**
  13870. * Set the value of an uniform to an array of float32 (stored as vec4)
  13871. * @param uniform defines the webGL uniform location where to store the value
  13872. * @param array defines the array of float32 to store
  13873. */
  13874. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13875. if (!uniform || array.length % 4 !== 0)
  13876. return;
  13877. this._gl.uniform4fv(uniform, array);
  13878. };
  13879. /**
  13880. * Set the value of an uniform to an array of number
  13881. * @param uniform defines the webGL uniform location where to store the value
  13882. * @param array defines the array of number to store
  13883. */
  13884. Engine.prototype.setArray = function (uniform, array) {
  13885. if (!uniform)
  13886. return;
  13887. this._gl.uniform1fv(uniform, array);
  13888. };
  13889. /**
  13890. * Set the value of an uniform to an array of number (stored as vec2)
  13891. * @param uniform defines the webGL uniform location where to store the value
  13892. * @param array defines the array of number to store
  13893. */
  13894. Engine.prototype.setArray2 = function (uniform, array) {
  13895. if (!uniform || array.length % 2 !== 0)
  13896. return;
  13897. this._gl.uniform2fv(uniform, array);
  13898. };
  13899. /**
  13900. * Set the value of an uniform to an array of number (stored as vec3)
  13901. * @param uniform defines the webGL uniform location where to store the value
  13902. * @param array defines the array of number to store
  13903. */
  13904. Engine.prototype.setArray3 = function (uniform, array) {
  13905. if (!uniform || array.length % 3 !== 0)
  13906. return;
  13907. this._gl.uniform3fv(uniform, array);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to an array of number (stored as vec4)
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param array defines the array of number to store
  13913. */
  13914. Engine.prototype.setArray4 = function (uniform, array) {
  13915. if (!uniform || array.length % 4 !== 0)
  13916. return;
  13917. this._gl.uniform4fv(uniform, array);
  13918. };
  13919. /**
  13920. * Set the value of an uniform to an array of float32 (stored as matrices)
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param matrices defines the array of float32 to store
  13923. */
  13924. Engine.prototype.setMatrices = function (uniform, matrices) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to a matrix
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param matrix defines the matrix to store
  13933. */
  13934. Engine.prototype.setMatrix = function (uniform, matrix) {
  13935. if (!uniform)
  13936. return;
  13937. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13938. };
  13939. /**
  13940. * Set the value of an uniform to a matrix (3x3)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13943. */
  13944. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13945. if (!uniform)
  13946. return;
  13947. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to a matrix (2x2)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13953. */
  13954. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13955. if (!uniform)
  13956. return;
  13957. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to a number (int)
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param value defines the int number to store
  13963. */
  13964. Engine.prototype.setInt = function (uniform, value) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform1i(uniform, value);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to a number (float)
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param value defines the float number to store
  13973. */
  13974. Engine.prototype.setFloat = function (uniform, value) {
  13975. if (!uniform)
  13976. return;
  13977. this._gl.uniform1f(uniform, value);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to a vec2
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param x defines the 1st component of the value
  13983. * @param y defines the 2nd component of the value
  13984. */
  13985. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13986. if (!uniform)
  13987. return;
  13988. this._gl.uniform2f(uniform, x, y);
  13989. };
  13990. /**
  13991. * Set the value of an uniform to a vec3
  13992. * @param uniform defines the webGL uniform location where to store the value
  13993. * @param x defines the 1st component of the value
  13994. * @param y defines the 2nd component of the value
  13995. * @param z defines the 3rd component of the value
  13996. */
  13997. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13998. if (!uniform)
  13999. return;
  14000. this._gl.uniform3f(uniform, x, y, z);
  14001. };
  14002. /**
  14003. * Set the value of an uniform to a boolean
  14004. * @param uniform defines the webGL uniform location where to store the value
  14005. * @param bool defines the boolean to store
  14006. */
  14007. Engine.prototype.setBool = function (uniform, bool) {
  14008. if (!uniform)
  14009. return;
  14010. this._gl.uniform1i(uniform, bool);
  14011. };
  14012. /**
  14013. * Set the value of an uniform to a vec4
  14014. * @param uniform defines the webGL uniform location where to store the value
  14015. * @param x defines the 1st component of the value
  14016. * @param y defines the 2nd component of the value
  14017. * @param z defines the 3rd component of the value
  14018. * @param w defines the 4th component of the value
  14019. */
  14020. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14021. if (!uniform)
  14022. return;
  14023. this._gl.uniform4f(uniform, x, y, z, w);
  14024. };
  14025. /**
  14026. * Set the value of an uniform to a Color3
  14027. * @param uniform defines the webGL uniform location where to store the value
  14028. * @param color3 defines the color to store
  14029. */
  14030. Engine.prototype.setColor3 = function (uniform, color3) {
  14031. if (!uniform)
  14032. return;
  14033. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14034. };
  14035. /**
  14036. * Set the value of an uniform to a Color3 and an alpha value
  14037. * @param uniform defines the webGL uniform location where to store the value
  14038. * @param color3 defines the color to store
  14039. * @param alpha defines the alpha component to store
  14040. */
  14041. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14042. if (!uniform)
  14043. return;
  14044. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14045. };
  14046. /**
  14047. * Sets a Color4 on a uniform variable
  14048. * @param uniform defines the uniform location
  14049. * @param color4 defines the value to be set
  14050. */
  14051. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14052. if (!uniform)
  14053. return;
  14054. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14055. };
  14056. // States
  14057. /**
  14058. * Set various states to the webGL context
  14059. * @param culling defines backface culling state
  14060. * @param zOffset defines the value to apply to zOffset (0 by default)
  14061. * @param force defines if states must be applied even if cache is up to date
  14062. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14063. */
  14064. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14065. if (zOffset === void 0) { zOffset = 0; }
  14066. if (reverseSide === void 0) { reverseSide = false; }
  14067. // Culling
  14068. if (this._depthCullingState.cull !== culling || force) {
  14069. this._depthCullingState.cull = culling;
  14070. }
  14071. // Cull face
  14072. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14073. if (this._depthCullingState.cullFace !== cullFace || force) {
  14074. this._depthCullingState.cullFace = cullFace;
  14075. }
  14076. // Z offset
  14077. this.setZOffset(zOffset);
  14078. // Front face
  14079. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14080. if (this._depthCullingState.frontFace !== frontFace || force) {
  14081. this._depthCullingState.frontFace = frontFace;
  14082. }
  14083. };
  14084. /**
  14085. * Set the z offset to apply to current rendering
  14086. * @param value defines the offset to apply
  14087. */
  14088. Engine.prototype.setZOffset = function (value) {
  14089. this._depthCullingState.zOffset = value;
  14090. };
  14091. /**
  14092. * Gets the current value of the zOffset
  14093. * @returns the current zOffset state
  14094. */
  14095. Engine.prototype.getZOffset = function () {
  14096. return this._depthCullingState.zOffset;
  14097. };
  14098. /**
  14099. * Enable or disable depth buffering
  14100. * @param enable defines the state to set
  14101. */
  14102. Engine.prototype.setDepthBuffer = function (enable) {
  14103. this._depthCullingState.depthTest = enable;
  14104. };
  14105. /**
  14106. * Gets a boolean indicating if depth writing is enabled
  14107. * @returns the current depth writing state
  14108. */
  14109. Engine.prototype.getDepthWrite = function () {
  14110. return this._depthCullingState.depthMask;
  14111. };
  14112. /**
  14113. * Enable or disable depth writing
  14114. * @param enable defines the state to set
  14115. */
  14116. Engine.prototype.setDepthWrite = function (enable) {
  14117. this._depthCullingState.depthMask = enable;
  14118. };
  14119. /**
  14120. * Enable or disable color writing
  14121. * @param enable defines the state to set
  14122. */
  14123. Engine.prototype.setColorWrite = function (enable) {
  14124. this._gl.colorMask(enable, enable, enable, enable);
  14125. this._colorWrite = enable;
  14126. };
  14127. /**
  14128. * Gets a boolean indicating if color writing is enabled
  14129. * @returns the current color writing state
  14130. */
  14131. Engine.prototype.getColorWrite = function () {
  14132. return this._colorWrite;
  14133. };
  14134. /**
  14135. * Sets alpha constants used by some alpha blending modes
  14136. * @param r defines the red component
  14137. * @param g defines the green component
  14138. * @param b defines the blue component
  14139. * @param a defines the alpha component
  14140. */
  14141. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14142. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14143. };
  14144. /**
  14145. * Sets the current alpha mode
  14146. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14147. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14148. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14149. */
  14150. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14151. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14152. if (this._alphaMode === mode) {
  14153. return;
  14154. }
  14155. switch (mode) {
  14156. case Engine.ALPHA_DISABLE:
  14157. this._alphaState.alphaBlend = false;
  14158. break;
  14159. case Engine.ALPHA_PREMULTIPLIED:
  14160. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14161. this._alphaState.alphaBlend = true;
  14162. break;
  14163. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14164. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14165. this._alphaState.alphaBlend = true;
  14166. break;
  14167. case Engine.ALPHA_COMBINE:
  14168. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14169. this._alphaState.alphaBlend = true;
  14170. break;
  14171. case Engine.ALPHA_ONEONE:
  14172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14173. this._alphaState.alphaBlend = true;
  14174. break;
  14175. case Engine.ALPHA_ADD:
  14176. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14177. this._alphaState.alphaBlend = true;
  14178. break;
  14179. case Engine.ALPHA_SUBTRACT:
  14180. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14181. this._alphaState.alphaBlend = true;
  14182. break;
  14183. case Engine.ALPHA_MULTIPLY:
  14184. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14185. this._alphaState.alphaBlend = true;
  14186. break;
  14187. case Engine.ALPHA_MAXIMIZED:
  14188. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14189. this._alphaState.alphaBlend = true;
  14190. break;
  14191. case Engine.ALPHA_INTERPOLATE:
  14192. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14193. this._alphaState.alphaBlend = true;
  14194. break;
  14195. case Engine.ALPHA_SCREENMODE:
  14196. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14197. this._alphaState.alphaBlend = true;
  14198. break;
  14199. }
  14200. if (!noDepthWriteChange) {
  14201. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14202. }
  14203. this._alphaMode = mode;
  14204. };
  14205. /**
  14206. * Gets the current alpha mode
  14207. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14208. * @returns the current alpha mode
  14209. */
  14210. Engine.prototype.getAlphaMode = function () {
  14211. return this._alphaMode;
  14212. };
  14213. // Textures
  14214. /**
  14215. * Clears the list of texture accessible through engine.
  14216. * This can help preventing texture load conflict due to name collision.
  14217. */
  14218. Engine.prototype.clearInternalTexturesCache = function () {
  14219. this._internalTexturesCache = [];
  14220. };
  14221. /**
  14222. * Force the entire cache to be cleared
  14223. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14224. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14225. */
  14226. Engine.prototype.wipeCaches = function (bruteForce) {
  14227. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14228. return;
  14229. }
  14230. this._currentEffect = null;
  14231. this._unpackFlipYCached = null;
  14232. this._viewportCached.x = 0;
  14233. this._viewportCached.y = 0;
  14234. this._viewportCached.z = 0;
  14235. this._viewportCached.w = 0;
  14236. if (bruteForce) {
  14237. this.resetTextureCache();
  14238. this._currentProgram = null;
  14239. this._stencilState.reset();
  14240. this._depthCullingState.reset();
  14241. this.setDepthFunctionToLessOrEqual();
  14242. this._alphaState.reset();
  14243. }
  14244. this._resetVertexBufferBinding();
  14245. this._cachedIndexBuffer = null;
  14246. this._cachedEffectForVertexBuffers = null;
  14247. this._unbindVertexArrayObject();
  14248. this.bindIndexBuffer(null);
  14249. };
  14250. /**
  14251. * Set the compressed texture format to use, based on the formats you have, and the formats
  14252. * supported by the hardware / browser.
  14253. *
  14254. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14255. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14256. * to API arguments needed to compressed textures. This puts the burden on the container
  14257. * generator to house the arcane code for determining these for current & future formats.
  14258. *
  14259. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14260. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14261. *
  14262. * Note: The result of this call is not taken into account when a texture is base64.
  14263. *
  14264. * @param formatsAvailable defines the list of those format families you have created
  14265. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14266. *
  14267. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14268. * @returns The extension selected.
  14269. */
  14270. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14271. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14272. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14273. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14274. return this._textureFormatInUse = this._texturesSupported[i];
  14275. }
  14276. }
  14277. }
  14278. // actively set format to nothing, to allow this to be called more than once
  14279. // and possibly fail the 2nd time
  14280. this._textureFormatInUse = null;
  14281. return null;
  14282. };
  14283. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14284. var gl = this._gl;
  14285. var magFilter = gl.NEAREST;
  14286. var minFilter = gl.NEAREST;
  14287. switch (samplingMode) {
  14288. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14289. magFilter = gl.LINEAR;
  14290. if (generateMipMaps) {
  14291. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14292. }
  14293. else {
  14294. minFilter = gl.LINEAR;
  14295. }
  14296. break;
  14297. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14298. magFilter = gl.LINEAR;
  14299. if (generateMipMaps) {
  14300. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14301. }
  14302. else {
  14303. minFilter = gl.LINEAR;
  14304. }
  14305. break;
  14306. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14307. magFilter = gl.NEAREST;
  14308. if (generateMipMaps) {
  14309. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14310. }
  14311. else {
  14312. minFilter = gl.NEAREST;
  14313. }
  14314. break;
  14315. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14316. magFilter = gl.NEAREST;
  14317. if (generateMipMaps) {
  14318. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14319. }
  14320. else {
  14321. minFilter = gl.NEAREST;
  14322. }
  14323. break;
  14324. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14325. magFilter = gl.NEAREST;
  14326. if (generateMipMaps) {
  14327. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14328. }
  14329. else {
  14330. minFilter = gl.LINEAR;
  14331. }
  14332. break;
  14333. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14334. magFilter = gl.NEAREST;
  14335. if (generateMipMaps) {
  14336. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14337. }
  14338. else {
  14339. minFilter = gl.LINEAR;
  14340. }
  14341. break;
  14342. case Engine.TEXTURE_NEAREST_LINEAR:
  14343. magFilter = gl.NEAREST;
  14344. minFilter = gl.LINEAR;
  14345. break;
  14346. case Engine.TEXTURE_NEAREST_NEAREST:
  14347. magFilter = gl.NEAREST;
  14348. minFilter = gl.NEAREST;
  14349. break;
  14350. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14351. magFilter = gl.LINEAR;
  14352. if (generateMipMaps) {
  14353. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14354. }
  14355. else {
  14356. minFilter = gl.NEAREST;
  14357. }
  14358. break;
  14359. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14360. magFilter = gl.LINEAR;
  14361. if (generateMipMaps) {
  14362. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14363. }
  14364. else {
  14365. minFilter = gl.NEAREST;
  14366. }
  14367. break;
  14368. case Engine.TEXTURE_LINEAR_LINEAR:
  14369. magFilter = gl.LINEAR;
  14370. minFilter = gl.LINEAR;
  14371. break;
  14372. case Engine.TEXTURE_LINEAR_NEAREST:
  14373. magFilter = gl.LINEAR;
  14374. minFilter = gl.NEAREST;
  14375. break;
  14376. }
  14377. return {
  14378. min: minFilter,
  14379. mag: magFilter
  14380. };
  14381. };
  14382. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14383. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14384. var img;
  14385. var onload = function () {
  14386. loadedImages[index] = img;
  14387. loadedImages._internalCount++;
  14388. if (scene) {
  14389. scene._removePendingData(img);
  14390. }
  14391. if (loadedImages._internalCount === 6) {
  14392. onfinish(loadedImages);
  14393. }
  14394. };
  14395. var onerror = function (message, exception) {
  14396. if (scene) {
  14397. scene._removePendingData(img);
  14398. }
  14399. if (onErrorCallBack) {
  14400. onErrorCallBack(message, exception);
  14401. }
  14402. };
  14403. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14404. if (scene) {
  14405. scene._addPendingData(img);
  14406. }
  14407. };
  14408. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14409. if (onError === void 0) { onError = null; }
  14410. var loadedImages = [];
  14411. loadedImages._internalCount = 0;
  14412. for (var index = 0; index < 6; index++) {
  14413. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14414. }
  14415. };
  14416. ;
  14417. /** @hidden */
  14418. Engine.prototype._createTexture = function () {
  14419. var texture = this._gl.createTexture();
  14420. if (!texture) {
  14421. throw new Error("Unable to create texture");
  14422. }
  14423. return texture;
  14424. };
  14425. /**
  14426. * Usually called from BABYLON.Texture.ts.
  14427. * Passed information to create a WebGLTexture
  14428. * @param urlArg defines a value which contains one of the following:
  14429. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14430. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14431. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14432. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14433. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14434. * @param scene needed for loading to the correct scene
  14435. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14436. * @param onLoad optional callback to be called upon successful completion
  14437. * @param onError optional callback to be called upon failure
  14438. * @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
  14439. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14440. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14441. * @param forcedExtension defines the extension to use to pick the right loader
  14442. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14443. */
  14444. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14445. var _this = this;
  14446. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14447. if (onLoad === void 0) { onLoad = null; }
  14448. if (onError === void 0) { onError = null; }
  14449. if (buffer === void 0) { buffer = null; }
  14450. if (fallback === void 0) { fallback = null; }
  14451. if (format === void 0) { format = null; }
  14452. if (forcedExtension === void 0) { forcedExtension = null; }
  14453. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14454. var fromData = url.substr(0, 5) === "data:";
  14455. var fromBlob = url.substr(0, 5) === "blob:";
  14456. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14457. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14458. // establish the file extension, if possible
  14459. var lastDot = url.lastIndexOf('.');
  14460. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14461. var loader = null;
  14462. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14463. var availableLoader = _a[_i];
  14464. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14465. loader = availableLoader;
  14466. break;
  14467. }
  14468. }
  14469. if (loader) {
  14470. url = loader.transformUrl(url, this._textureFormatInUse);
  14471. }
  14472. if (scene) {
  14473. scene._addPendingData(texture);
  14474. }
  14475. texture.url = url;
  14476. texture.generateMipMaps = !noMipmap;
  14477. texture.samplingMode = samplingMode;
  14478. texture.invertY = invertY;
  14479. if (!this._doNotHandleContextLost) {
  14480. // Keep a link to the buffer only if we plan to handle context lost
  14481. texture._buffer = buffer;
  14482. }
  14483. var onLoadObserver = null;
  14484. if (onLoad && !fallback) {
  14485. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14486. }
  14487. if (!fallback)
  14488. this._internalTexturesCache.push(texture);
  14489. var onInternalError = function (message, exception) {
  14490. if (scene) {
  14491. scene._removePendingData(texture);
  14492. }
  14493. var customFallback = false;
  14494. if (loader) {
  14495. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14496. if (fallbackUrl) {
  14497. // Add Back
  14498. customFallback = true;
  14499. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14500. }
  14501. }
  14502. if (!customFallback) {
  14503. if (onLoadObserver) {
  14504. texture.onLoadedObservable.remove(onLoadObserver);
  14505. }
  14506. if (BABYLON.Tools.UseFallbackTexture) {
  14507. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14508. }
  14509. }
  14510. if (onError) {
  14511. onError(message || "Unknown error", exception);
  14512. }
  14513. };
  14514. // processing for non-image formats
  14515. if (loader) {
  14516. var callback = function (data) {
  14517. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14518. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14519. done();
  14520. return false;
  14521. }, samplingMode);
  14522. });
  14523. };
  14524. if (!buffer) {
  14525. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14526. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14527. });
  14528. }
  14529. else {
  14530. callback(buffer);
  14531. }
  14532. }
  14533. else {
  14534. var onload = function (img) {
  14535. if (fromBlob && !_this._doNotHandleContextLost) {
  14536. // We need to store the image if we need to rebuild the texture
  14537. // in case of a webgl context lost
  14538. texture._buffer = img;
  14539. }
  14540. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14541. var gl = _this._gl;
  14542. var isPot = (img.width === potWidth && img.height === potHeight);
  14543. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14544. if (isPot) {
  14545. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14546. return false;
  14547. }
  14548. var maxTextureSize = _this._caps.maxTextureSize;
  14549. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14550. _this._prepareWorkingCanvas();
  14551. if (!_this._workingCanvas || !_this._workingContext) {
  14552. return false;
  14553. }
  14554. _this._workingCanvas.width = potWidth;
  14555. _this._workingCanvas.height = potHeight;
  14556. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14557. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14558. texture.width = potWidth;
  14559. texture.height = potHeight;
  14560. return false;
  14561. }
  14562. else {
  14563. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14564. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14565. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14566. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14571. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14572. _this._releaseTexture(source_1);
  14573. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14574. continuationCallback();
  14575. });
  14576. }
  14577. return true;
  14578. }, samplingMode);
  14579. };
  14580. if (!fromData || isBase64) {
  14581. if (buffer instanceof HTMLImageElement) {
  14582. onload(buffer);
  14583. }
  14584. else {
  14585. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14586. }
  14587. }
  14588. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14589. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14590. }
  14591. else {
  14592. onload(buffer);
  14593. }
  14594. }
  14595. return texture;
  14596. };
  14597. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14598. var _this = this;
  14599. var rtt = this.createRenderTargetTexture({
  14600. width: destination.width,
  14601. height: destination.height,
  14602. }, {
  14603. generateMipMaps: false,
  14604. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14605. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14606. generateDepthBuffer: false,
  14607. generateStencilBuffer: false
  14608. });
  14609. if (!this._rescalePostProcess) {
  14610. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14611. }
  14612. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14613. _this._rescalePostProcess.onApply = function (effect) {
  14614. effect._bindTexture("textureSampler", source);
  14615. };
  14616. var hostingScene = scene;
  14617. if (!hostingScene) {
  14618. hostingScene = _this.scenes[_this.scenes.length - 1];
  14619. }
  14620. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14621. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14622. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14623. _this.unBindFramebuffer(rtt);
  14624. _this._releaseTexture(rtt);
  14625. if (onComplete) {
  14626. onComplete();
  14627. }
  14628. });
  14629. };
  14630. /**
  14631. * Update a raw texture
  14632. * @param texture defines the texture to update
  14633. * @param data defines the data to store in the texture
  14634. * @param format defines the format of the data
  14635. * @param invertY defines if data must be stored with Y axis inverted
  14636. * @param compression defines the compression used (null by default)
  14637. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14638. */
  14639. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14640. if (compression === void 0) { compression = null; }
  14641. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14642. if (!texture) {
  14643. return;
  14644. }
  14645. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14646. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14647. // babylon's internalFormat but gl's texImage2D format
  14648. var internalFormat = this._getInternalFormat(format);
  14649. var textureType = this._getWebGLTextureType(type);
  14650. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14651. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14652. if (!this._doNotHandleContextLost) {
  14653. texture._bufferView = data;
  14654. texture.format = format;
  14655. texture.type = type;
  14656. texture.invertY = invertY;
  14657. texture._compression = compression;
  14658. }
  14659. if (texture.width % 4 !== 0) {
  14660. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14661. }
  14662. if (compression && data) {
  14663. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14664. }
  14665. else {
  14666. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14667. }
  14668. if (texture.generateMipMaps) {
  14669. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14670. }
  14671. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14672. // this.resetTextureCache();
  14673. texture.isReady = true;
  14674. };
  14675. /**
  14676. * Creates a raw texture
  14677. * @param data defines the data to store in the texture
  14678. * @param width defines the width of the texture
  14679. * @param height defines the height of the texture
  14680. * @param format defines the format of the data
  14681. * @param generateMipMaps defines if the engine should generate the mip levels
  14682. * @param invertY defines if data must be stored with Y axis inverted
  14683. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14684. * @param compression defines the compression used (null by default)
  14685. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14686. * @returns the raw texture inside an InternalTexture
  14687. */
  14688. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14689. if (compression === void 0) { compression = null; }
  14690. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14691. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14692. texture.baseWidth = width;
  14693. texture.baseHeight = height;
  14694. texture.width = width;
  14695. texture.height = height;
  14696. texture.format = format;
  14697. texture.generateMipMaps = generateMipMaps;
  14698. texture.samplingMode = samplingMode;
  14699. texture.invertY = invertY;
  14700. texture._compression = compression;
  14701. texture.type = type;
  14702. if (!this._doNotHandleContextLost) {
  14703. texture._bufferView = data;
  14704. }
  14705. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14706. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14707. // Filters
  14708. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14709. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14710. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14711. if (generateMipMaps) {
  14712. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14713. }
  14714. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14715. this._internalTexturesCache.push(texture);
  14716. return texture;
  14717. };
  14718. /** @hidden */
  14719. Engine.prototype._unpackFlipY = function (value) {
  14720. if (this._unpackFlipYCached !== value) {
  14721. this._unpackFlipYCached = value;
  14722. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14723. }
  14724. };
  14725. /** @hidden */
  14726. Engine.prototype._getUnpackAlignement = function () {
  14727. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14728. };
  14729. /**
  14730. * Creates a dynamic texture
  14731. * @param width defines the width of the texture
  14732. * @param height defines the height of the texture
  14733. * @param generateMipMaps defines if the engine should generate the mip levels
  14734. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14735. * @returns the dynamic texture inside an InternalTexture
  14736. */
  14737. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14738. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14739. texture.baseWidth = width;
  14740. texture.baseHeight = height;
  14741. if (generateMipMaps) {
  14742. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14743. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14744. }
  14745. // this.resetTextureCache();
  14746. texture.width = width;
  14747. texture.height = height;
  14748. texture.isReady = false;
  14749. texture.generateMipMaps = generateMipMaps;
  14750. texture.samplingMode = samplingMode;
  14751. this.updateTextureSamplingMode(samplingMode, texture);
  14752. this._internalTexturesCache.push(texture);
  14753. return texture;
  14754. };
  14755. /**
  14756. * Update the sampling mode of a given texture
  14757. * @param samplingMode defines the required sampling mode
  14758. * @param texture defines the texture to update
  14759. */
  14760. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14761. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14762. if (texture.isCube) {
  14763. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14764. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14765. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14766. }
  14767. else if (texture.is3D) {
  14768. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14769. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14770. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14771. }
  14772. else {
  14773. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14774. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14775. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14776. }
  14777. texture.samplingMode = samplingMode;
  14778. };
  14779. /**
  14780. * Update the content of a dynamic texture
  14781. * @param texture defines the texture to update
  14782. * @param canvas defines the canvas containing the source
  14783. * @param invertY defines if data must be stored with Y axis inverted
  14784. * @param premulAlpha defines if alpha is stored as premultiplied
  14785. * @param format defines the format of the data
  14786. */
  14787. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14788. if (premulAlpha === void 0) { premulAlpha = false; }
  14789. if (!texture) {
  14790. return;
  14791. }
  14792. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14793. this._unpackFlipY(invertY);
  14794. if (premulAlpha) {
  14795. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14796. }
  14797. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14798. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14799. if (texture.generateMipMaps) {
  14800. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14801. }
  14802. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14803. if (premulAlpha) {
  14804. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14805. }
  14806. texture.isReady = true;
  14807. };
  14808. /**
  14809. * Update a video texture
  14810. * @param texture defines the texture to update
  14811. * @param video defines the video element to use
  14812. * @param invertY defines if data must be stored with Y axis inverted
  14813. */
  14814. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14815. if (!texture || texture._isDisabled) {
  14816. return;
  14817. }
  14818. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14819. this._unpackFlipY(!invertY); // Video are upside down by default
  14820. try {
  14821. // Testing video texture support
  14822. if (this._videoTextureSupported === undefined) {
  14823. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14824. if (this._gl.getError() !== 0) {
  14825. this._videoTextureSupported = false;
  14826. }
  14827. else {
  14828. this._videoTextureSupported = true;
  14829. }
  14830. }
  14831. // Copy video through the current working canvas if video texture is not supported
  14832. if (!this._videoTextureSupported) {
  14833. if (!texture._workingCanvas) {
  14834. texture._workingCanvas = document.createElement("canvas");
  14835. var context = texture._workingCanvas.getContext("2d");
  14836. if (!context) {
  14837. throw new Error("Unable to get 2d context");
  14838. }
  14839. texture._workingContext = context;
  14840. texture._workingCanvas.width = texture.width;
  14841. texture._workingCanvas.height = texture.height;
  14842. }
  14843. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14844. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14845. }
  14846. else {
  14847. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14848. }
  14849. if (texture.generateMipMaps) {
  14850. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14851. }
  14852. if (!wasPreviouslyBound) {
  14853. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14854. }
  14855. // this.resetTextureCache();
  14856. texture.isReady = true;
  14857. }
  14858. catch (ex) {
  14859. // Something unexpected
  14860. // Let's disable the texture
  14861. texture._isDisabled = true;
  14862. }
  14863. };
  14864. /**
  14865. * Updates a depth texture Comparison Mode and Function.
  14866. * If the comparison Function is equal to 0, the mode will be set to none.
  14867. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14868. * @param texture The texture to set the comparison function for
  14869. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14870. */
  14871. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14872. if (this.webGLVersion === 1) {
  14873. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14874. return;
  14875. }
  14876. var gl = this._gl;
  14877. if (texture.isCube) {
  14878. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14879. if (comparisonFunction === 0) {
  14880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14882. }
  14883. else {
  14884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14886. }
  14887. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14888. }
  14889. else {
  14890. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14891. if (comparisonFunction === 0) {
  14892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14894. }
  14895. else {
  14896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14898. }
  14899. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14900. }
  14901. texture._comparisonFunction = comparisonFunction;
  14902. };
  14903. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14904. var width = size.width || size;
  14905. var height = size.height || size;
  14906. internalTexture.baseWidth = width;
  14907. internalTexture.baseHeight = height;
  14908. internalTexture.width = width;
  14909. internalTexture.height = height;
  14910. internalTexture.isReady = true;
  14911. internalTexture.samples = 1;
  14912. internalTexture.generateMipMaps = false;
  14913. internalTexture._generateDepthBuffer = true;
  14914. internalTexture._generateStencilBuffer = generateStencil;
  14915. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14916. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14917. internalTexture._comparisonFunction = comparisonFunction;
  14918. var gl = this._gl;
  14919. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14920. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14921. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14922. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14923. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14924. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14925. if (comparisonFunction === 0) {
  14926. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14927. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14928. }
  14929. else {
  14930. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14931. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14932. }
  14933. };
  14934. /**
  14935. * Creates a depth stencil texture.
  14936. * This is only available in WebGL 2 or with the depth texture extension available.
  14937. * @param size The size of face edge in the texture.
  14938. * @param options The options defining the texture.
  14939. * @returns The texture
  14940. */
  14941. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14942. if (options.isCube) {
  14943. var width = size.width || size;
  14944. return this._createDepthStencilCubeTexture(width, options);
  14945. }
  14946. else {
  14947. return this._createDepthStencilTexture(size, options);
  14948. }
  14949. };
  14950. /**
  14951. * Creates a depth stencil texture.
  14952. * This is only available in WebGL 2 or with the depth texture extension available.
  14953. * @param size The size of face edge in the texture.
  14954. * @param options The options defining the texture.
  14955. * @returns The texture
  14956. */
  14957. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14958. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14959. if (!this._caps.depthTextureExtension) {
  14960. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14961. return internalTexture;
  14962. }
  14963. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14964. var gl = this._gl;
  14965. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14966. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14967. if (this.webGLVersion > 1) {
  14968. if (internalOptions.generateStencil) {
  14969. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14970. }
  14971. else {
  14972. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14973. }
  14974. }
  14975. else {
  14976. if (internalOptions.generateStencil) {
  14977. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14978. }
  14979. else {
  14980. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14981. }
  14982. }
  14983. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14984. return internalTexture;
  14985. };
  14986. /**
  14987. * Creates a depth stencil cube texture.
  14988. * This is only available in WebGL 2.
  14989. * @param size The size of face edge in the cube texture.
  14990. * @param options The options defining the cube texture.
  14991. * @returns The cube texture
  14992. */
  14993. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14994. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14995. internalTexture.isCube = true;
  14996. if (this.webGLVersion === 1) {
  14997. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14998. return internalTexture;
  14999. }
  15000. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15001. var gl = this._gl;
  15002. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15003. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15004. // Create the depth/stencil buffer
  15005. for (var face = 0; face < 6; face++) {
  15006. if (internalOptions.generateStencil) {
  15007. 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);
  15008. }
  15009. else {
  15010. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15011. }
  15012. }
  15013. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15014. return internalTexture;
  15015. };
  15016. /**
  15017. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15018. * @param renderTarget The render target to set the frame buffer for
  15019. */
  15020. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15021. // Create the framebuffer
  15022. var internalTexture = renderTarget.getInternalTexture();
  15023. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15024. return;
  15025. }
  15026. var gl = this._gl;
  15027. var depthStencilTexture = renderTarget.depthStencilTexture;
  15028. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15029. if (depthStencilTexture.isCube) {
  15030. if (depthStencilTexture._generateStencilBuffer) {
  15031. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15032. }
  15033. else {
  15034. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15035. }
  15036. }
  15037. else {
  15038. if (depthStencilTexture._generateStencilBuffer) {
  15039. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15040. }
  15041. else {
  15042. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15043. }
  15044. }
  15045. this.bindUnboundFramebuffer(null);
  15046. };
  15047. /**
  15048. * Creates a new render target texture
  15049. * @param size defines the size of the texture
  15050. * @param options defines the options used to create the texture
  15051. * @returns a new render target texture stored in an InternalTexture
  15052. */
  15053. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15054. var fullOptions = new RenderTargetCreationOptions();
  15055. if (options !== undefined && typeof options === "object") {
  15056. fullOptions.generateMipMaps = options.generateMipMaps;
  15057. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15058. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15059. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15060. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15061. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15062. }
  15063. else {
  15064. fullOptions.generateMipMaps = options;
  15065. fullOptions.generateDepthBuffer = true;
  15066. fullOptions.generateStencilBuffer = false;
  15067. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15068. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15069. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15070. }
  15071. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15072. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15073. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15074. }
  15075. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15076. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15077. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15078. }
  15079. var gl = this._gl;
  15080. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15081. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15082. var width = size.width || size;
  15083. var height = size.height || size;
  15084. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15085. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15086. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15087. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15088. }
  15089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15090. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15093. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15094. // Create the framebuffer
  15095. var currentFrameBuffer = this._currentFramebuffer;
  15096. var framebuffer = gl.createFramebuffer();
  15097. this.bindUnboundFramebuffer(framebuffer);
  15098. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15099. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15100. if (fullOptions.generateMipMaps) {
  15101. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15102. }
  15103. // Unbind
  15104. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15105. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15106. this.bindUnboundFramebuffer(currentFrameBuffer);
  15107. texture._framebuffer = framebuffer;
  15108. texture.baseWidth = width;
  15109. texture.baseHeight = height;
  15110. texture.width = width;
  15111. texture.height = height;
  15112. texture.isReady = true;
  15113. texture.samples = 1;
  15114. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15115. texture.samplingMode = fullOptions.samplingMode;
  15116. texture.type = fullOptions.type;
  15117. texture.format = fullOptions.format;
  15118. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15119. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15120. // this.resetTextureCache();
  15121. this._internalTexturesCache.push(texture);
  15122. return texture;
  15123. };
  15124. /**
  15125. * Create a multi render target texture
  15126. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15127. * @param size defines the size of the texture
  15128. * @param options defines the creation options
  15129. * @returns the cube texture as an InternalTexture
  15130. */
  15131. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15132. var generateMipMaps = false;
  15133. var generateDepthBuffer = true;
  15134. var generateStencilBuffer = false;
  15135. var generateDepthTexture = false;
  15136. var textureCount = 1;
  15137. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15138. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15139. var types = new Array();
  15140. var samplingModes = new Array();
  15141. if (options !== undefined) {
  15142. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15143. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15144. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15145. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15146. textureCount = options.textureCount || 1;
  15147. if (options.types) {
  15148. types = options.types;
  15149. }
  15150. if (options.samplingModes) {
  15151. samplingModes = options.samplingModes;
  15152. }
  15153. }
  15154. var gl = this._gl;
  15155. // Create the framebuffer
  15156. var framebuffer = gl.createFramebuffer();
  15157. this.bindUnboundFramebuffer(framebuffer);
  15158. var width = size.width || size;
  15159. var height = size.height || size;
  15160. var textures = [];
  15161. var attachments = [];
  15162. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15163. for (var i = 0; i < textureCount; i++) {
  15164. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15165. var type = types[i] || defaultType;
  15166. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15167. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15168. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15169. }
  15170. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15171. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15172. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15173. }
  15174. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15175. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15176. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15177. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15178. }
  15179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15180. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15181. textures.push(texture);
  15182. attachments.push(attachment);
  15183. gl.activeTexture(gl["TEXTURE" + i]);
  15184. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15185. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15186. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15187. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15188. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15189. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15190. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15191. if (generateMipMaps) {
  15192. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15193. }
  15194. // Unbind
  15195. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15196. texture._framebuffer = framebuffer;
  15197. texture._depthStencilBuffer = depthStencilBuffer;
  15198. texture.baseWidth = width;
  15199. texture.baseHeight = height;
  15200. texture.width = width;
  15201. texture.height = height;
  15202. texture.isReady = true;
  15203. texture.samples = 1;
  15204. texture.generateMipMaps = generateMipMaps;
  15205. texture.samplingMode = samplingMode;
  15206. texture.type = type;
  15207. texture._generateDepthBuffer = generateDepthBuffer;
  15208. texture._generateStencilBuffer = generateStencilBuffer;
  15209. texture._attachments = attachments;
  15210. this._internalTexturesCache.push(texture);
  15211. }
  15212. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15213. // Depth texture
  15214. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15215. gl.activeTexture(gl.TEXTURE0);
  15216. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15220. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15221. 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);
  15222. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15223. depthTexture._framebuffer = framebuffer;
  15224. depthTexture.baseWidth = width;
  15225. depthTexture.baseHeight = height;
  15226. depthTexture.width = width;
  15227. depthTexture.height = height;
  15228. depthTexture.isReady = true;
  15229. depthTexture.samples = 1;
  15230. depthTexture.generateMipMaps = generateMipMaps;
  15231. depthTexture.samplingMode = gl.NEAREST;
  15232. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15233. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15234. textures.push(depthTexture);
  15235. this._internalTexturesCache.push(depthTexture);
  15236. }
  15237. gl.drawBuffers(attachments);
  15238. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15239. this.bindUnboundFramebuffer(null);
  15240. this.resetTextureCache();
  15241. return textures;
  15242. };
  15243. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15244. if (samples === void 0) { samples = 1; }
  15245. var depthStencilBuffer = null;
  15246. var gl = this._gl;
  15247. // Create the depth/stencil buffer
  15248. if (generateStencilBuffer) {
  15249. depthStencilBuffer = gl.createRenderbuffer();
  15250. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15251. if (samples > 1) {
  15252. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15253. }
  15254. else {
  15255. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15256. }
  15257. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15258. }
  15259. else if (generateDepthBuffer) {
  15260. depthStencilBuffer = gl.createRenderbuffer();
  15261. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15262. if (samples > 1) {
  15263. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15264. }
  15265. else {
  15266. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15267. }
  15268. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15269. }
  15270. return depthStencilBuffer;
  15271. };
  15272. /**
  15273. * Updates the sample count of a render target texture
  15274. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15275. * @param texture defines the texture to update
  15276. * @param samples defines the sample count to set
  15277. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15278. */
  15279. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15280. if (this.webGLVersion < 2 || !texture) {
  15281. return 1;
  15282. }
  15283. if (texture.samples === samples) {
  15284. return samples;
  15285. }
  15286. var gl = this._gl;
  15287. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15288. // Dispose previous render buffers
  15289. if (texture._depthStencilBuffer) {
  15290. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15291. texture._depthStencilBuffer = null;
  15292. }
  15293. if (texture._MSAAFramebuffer) {
  15294. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15295. texture._MSAAFramebuffer = null;
  15296. }
  15297. if (texture._MSAARenderBuffer) {
  15298. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15299. texture._MSAARenderBuffer = null;
  15300. }
  15301. if (samples > 1) {
  15302. var framebuffer = gl.createFramebuffer();
  15303. if (!framebuffer) {
  15304. throw new Error("Unable to create multi sampled framebuffer");
  15305. }
  15306. texture._MSAAFramebuffer = framebuffer;
  15307. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15308. var colorRenderbuffer = gl.createRenderbuffer();
  15309. if (!colorRenderbuffer) {
  15310. throw new Error("Unable to create multi sampled framebuffer");
  15311. }
  15312. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15313. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15314. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15315. texture._MSAARenderBuffer = colorRenderbuffer;
  15316. }
  15317. else {
  15318. this.bindUnboundFramebuffer(texture._framebuffer);
  15319. }
  15320. texture.samples = samples;
  15321. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15322. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15323. this.bindUnboundFramebuffer(null);
  15324. return samples;
  15325. };
  15326. /**
  15327. * Update the sample count for a given multiple render target texture
  15328. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15329. * @param textures defines the textures to update
  15330. * @param samples defines the sample count to set
  15331. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15332. */
  15333. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15334. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15335. return 1;
  15336. }
  15337. if (textures[0].samples === samples) {
  15338. return samples;
  15339. }
  15340. var gl = this._gl;
  15341. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15342. // Dispose previous render buffers
  15343. if (textures[0]._depthStencilBuffer) {
  15344. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15345. textures[0]._depthStencilBuffer = null;
  15346. }
  15347. if (textures[0]._MSAAFramebuffer) {
  15348. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15349. textures[0]._MSAAFramebuffer = null;
  15350. }
  15351. for (var i = 0; i < textures.length; i++) {
  15352. if (textures[i]._MSAARenderBuffer) {
  15353. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15354. textures[i]._MSAARenderBuffer = null;
  15355. }
  15356. }
  15357. if (samples > 1) {
  15358. var framebuffer = gl.createFramebuffer();
  15359. if (!framebuffer) {
  15360. throw new Error("Unable to create multi sampled framebuffer");
  15361. }
  15362. this.bindUnboundFramebuffer(framebuffer);
  15363. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15364. var attachments = [];
  15365. for (var i = 0; i < textures.length; i++) {
  15366. var texture = textures[i];
  15367. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15368. var colorRenderbuffer = gl.createRenderbuffer();
  15369. if (!colorRenderbuffer) {
  15370. throw new Error("Unable to create multi sampled framebuffer");
  15371. }
  15372. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15373. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15374. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15375. texture._MSAAFramebuffer = framebuffer;
  15376. texture._MSAARenderBuffer = colorRenderbuffer;
  15377. texture.samples = samples;
  15378. texture._depthStencilBuffer = depthStencilBuffer;
  15379. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15380. attachments.push(attachment);
  15381. }
  15382. gl.drawBuffers(attachments);
  15383. }
  15384. else {
  15385. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15386. }
  15387. this.bindUnboundFramebuffer(null);
  15388. return samples;
  15389. };
  15390. /** @hidden */
  15391. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15392. if (faceIndex === void 0) { faceIndex = 0; }
  15393. if (lod === void 0) { lod = 0; }
  15394. var gl = this._gl;
  15395. var target = gl.TEXTURE_2D;
  15396. if (texture.isCube) {
  15397. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15398. }
  15399. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15400. };
  15401. /** @hidden */
  15402. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15403. if (faceIndex === void 0) { faceIndex = 0; }
  15404. if (lod === void 0) { lod = 0; }
  15405. var gl = this._gl;
  15406. var textureType = this._getWebGLTextureType(texture.type);
  15407. var format = this._getInternalFormat(texture.format);
  15408. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15409. this._unpackFlipY(texture.invertY);
  15410. var target = gl.TEXTURE_2D;
  15411. if (texture.isCube) {
  15412. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15413. }
  15414. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15415. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15416. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15417. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15418. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15419. };
  15420. /** @hidden */
  15421. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15422. if (faceIndex === void 0) { faceIndex = 0; }
  15423. if (lod === void 0) { lod = 0; }
  15424. var gl = this._gl;
  15425. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15426. this._bindTextureDirectly(bindTarget, texture, true);
  15427. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15428. this._bindTextureDirectly(bindTarget, null, true);
  15429. };
  15430. /** @hidden */
  15431. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15432. if (faceIndex === void 0) { faceIndex = 0; }
  15433. if (lod === void 0) { lod = 0; }
  15434. var gl = this._gl;
  15435. var textureType = this._getWebGLTextureType(texture.type);
  15436. var format = this._getInternalFormat(texture.format);
  15437. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15438. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15439. this._bindTextureDirectly(bindTarget, texture, true);
  15440. this._unpackFlipY(texture.invertY);
  15441. var target = gl.TEXTURE_2D;
  15442. if (texture.isCube) {
  15443. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15444. }
  15445. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15446. this._bindTextureDirectly(bindTarget, null, true);
  15447. };
  15448. /**
  15449. * Creates a new render target cube texture
  15450. * @param size defines the size of the texture
  15451. * @param options defines the options used to create the texture
  15452. * @returns a new render target cube texture stored in an InternalTexture
  15453. */
  15454. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15455. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15456. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15457. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15458. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15459. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15460. }
  15461. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15462. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15463. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15464. }
  15465. var gl = this._gl;
  15466. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15467. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15468. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15469. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15470. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15471. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15472. }
  15473. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15477. for (var face = 0; face < 6; face++) {
  15478. 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);
  15479. }
  15480. // Create the framebuffer
  15481. var framebuffer = gl.createFramebuffer();
  15482. this.bindUnboundFramebuffer(framebuffer);
  15483. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15484. // MipMaps
  15485. if (fullOptions.generateMipMaps) {
  15486. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15487. }
  15488. // Unbind
  15489. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15490. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15491. this.bindUnboundFramebuffer(null);
  15492. texture._framebuffer = framebuffer;
  15493. texture.width = size;
  15494. texture.height = size;
  15495. texture.isReady = true;
  15496. texture.isCube = true;
  15497. texture.samples = 1;
  15498. texture.generateMipMaps = fullOptions.generateMipMaps;
  15499. texture.samplingMode = fullOptions.samplingMode;
  15500. texture.type = fullOptions.type;
  15501. texture.format = fullOptions.format;
  15502. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15503. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15504. this._internalTexturesCache.push(texture);
  15505. return texture;
  15506. };
  15507. /**
  15508. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15509. * @param rootUrl defines the url where the file to load is located
  15510. * @param scene defines the current scene
  15511. * @param lodScale defines scale to apply to the mip map selection
  15512. * @param lodOffset defines offset to apply to the mip map selection
  15513. * @param onLoad defines an optional callback raised when the texture is loaded
  15514. * @param onError defines an optional callback raised if there is an issue to load the texture
  15515. * @param format defines the format of the data
  15516. * @param forcedExtension defines the extension to use to pick the right loader
  15517. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15518. * @returns the cube texture as an InternalTexture
  15519. */
  15520. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15521. var _this = this;
  15522. if (onLoad === void 0) { onLoad = null; }
  15523. if (onError === void 0) { onError = null; }
  15524. if (forcedExtension === void 0) { forcedExtension = null; }
  15525. if (createPolynomials === void 0) { createPolynomials = true; }
  15526. var callback = function (loadData) {
  15527. if (!loadData) {
  15528. if (onLoad) {
  15529. onLoad(null);
  15530. }
  15531. return;
  15532. }
  15533. var texture = loadData.texture;
  15534. if (!createPolynomials) {
  15535. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15536. }
  15537. else if (loadData.info.sphericalPolynomial) {
  15538. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15539. }
  15540. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15541. if (_this._caps.textureLOD) {
  15542. // Do not add extra process if texture lod is supported.
  15543. if (onLoad) {
  15544. onLoad(texture);
  15545. }
  15546. return;
  15547. }
  15548. var mipSlices = 3;
  15549. var gl = _this._gl;
  15550. var width = loadData.width;
  15551. if (!width) {
  15552. return;
  15553. }
  15554. var textures = [];
  15555. for (var i = 0; i < mipSlices; i++) {
  15556. //compute LOD from even spacing in smoothness (matching shader calculation)
  15557. var smoothness = i / (mipSlices - 1);
  15558. var roughness = 1 - smoothness;
  15559. var minLODIndex = lodOffset; // roughness = 0
  15560. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15561. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15562. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15563. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15564. glTextureFromLod.type = texture.type;
  15565. glTextureFromLod.format = texture.format;
  15566. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15567. glTextureFromLod.height = glTextureFromLod.width;
  15568. glTextureFromLod.isCube = true;
  15569. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15570. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15571. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15572. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15573. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15574. if (loadData.isDDS) {
  15575. var info = loadData.info;
  15576. var data = loadData.data;
  15577. _this._unpackFlipY(info.isCompressed);
  15578. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15579. }
  15580. else {
  15581. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15582. }
  15583. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15584. // Wrap in a base texture for easy binding.
  15585. var lodTexture = new BABYLON.BaseTexture(scene);
  15586. lodTexture.isCube = true;
  15587. lodTexture._texture = glTextureFromLod;
  15588. glTextureFromLod.isReady = true;
  15589. textures.push(lodTexture);
  15590. }
  15591. texture._lodTextureHigh = textures[2];
  15592. texture._lodTextureMid = textures[1];
  15593. texture._lodTextureLow = textures[0];
  15594. if (onLoad) {
  15595. onLoad(texture);
  15596. }
  15597. };
  15598. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15599. };
  15600. /**
  15601. * Creates a cube texture
  15602. * @param rootUrl defines the url where the files to load is located
  15603. * @param scene defines the current scene
  15604. * @param files defines the list of files to load (1 per face)
  15605. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15606. * @param onLoad defines an optional callback raised when the texture is loaded
  15607. * @param onError defines an optional callback raised if there is an issue to load the texture
  15608. * @param format defines the format of the data
  15609. * @param forcedExtension defines the extension to use to pick the right loader
  15610. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15611. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15612. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15613. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15614. * @returns the cube texture as an InternalTexture
  15615. */
  15616. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15617. var _this = this;
  15618. if (onLoad === void 0) { onLoad = null; }
  15619. if (onError === void 0) { onError = null; }
  15620. if (forcedExtension === void 0) { forcedExtension = null; }
  15621. if (createPolynomials === void 0) { createPolynomials = false; }
  15622. if (lodScale === void 0) { lodScale = 0; }
  15623. if (lodOffset === void 0) { lodOffset = 0; }
  15624. if (fallback === void 0) { fallback = null; }
  15625. var gl = this._gl;
  15626. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15627. texture.isCube = true;
  15628. texture.url = rootUrl;
  15629. texture.generateMipMaps = !noMipmap;
  15630. texture._lodGenerationScale = lodScale;
  15631. texture._lodGenerationOffset = lodOffset;
  15632. if (!this._doNotHandleContextLost) {
  15633. texture._extension = forcedExtension;
  15634. texture._files = files;
  15635. }
  15636. var lastDot = rootUrl.lastIndexOf('.');
  15637. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15638. var loader = null;
  15639. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15640. var availableLoader = _a[_i];
  15641. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15642. loader = availableLoader;
  15643. break;
  15644. }
  15645. }
  15646. var onInternalError = function (request, exception) {
  15647. if (loader) {
  15648. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15649. if (fallbackUrl) {
  15650. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15651. }
  15652. }
  15653. if (onError && request) {
  15654. onError(request.status + " " + request.statusText, exception);
  15655. }
  15656. };
  15657. if (loader) {
  15658. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15659. var onloaddata = function (data) {
  15660. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15661. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15662. };
  15663. if (files && files.length === 6) {
  15664. if (loader.supportCascades) {
  15665. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15666. }
  15667. else if (onError) {
  15668. onError("Textures type does not support cascades.");
  15669. }
  15670. }
  15671. else {
  15672. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15673. }
  15674. }
  15675. else {
  15676. if (!files) {
  15677. throw new Error("Cannot load cubemap because files were not defined");
  15678. }
  15679. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15680. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15681. var height = width;
  15682. _this._prepareWorkingCanvas();
  15683. if (!_this._workingCanvas || !_this._workingContext) {
  15684. return;
  15685. }
  15686. _this._workingCanvas.width = width;
  15687. _this._workingCanvas.height = height;
  15688. var faces = [
  15689. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15690. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15691. ];
  15692. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15693. _this._unpackFlipY(false);
  15694. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15695. for (var index = 0; index < faces.length; index++) {
  15696. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15697. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15698. }
  15699. if (!noMipmap) {
  15700. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15701. }
  15702. _this._setCubeMapTextureParams(!noMipmap);
  15703. texture.width = width;
  15704. texture.height = height;
  15705. texture.isReady = true;
  15706. if (format) {
  15707. texture.format = format;
  15708. }
  15709. texture.onLoadedObservable.notifyObservers(texture);
  15710. texture.onLoadedObservable.clear();
  15711. if (onLoad) {
  15712. onLoad();
  15713. }
  15714. }, files, onError);
  15715. }
  15716. this._internalTexturesCache.push(texture);
  15717. return texture;
  15718. };
  15719. /**
  15720. * @hidden
  15721. */
  15722. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15723. var gl = this._gl;
  15724. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15725. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15726. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15728. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15729. // this.resetTextureCache();
  15730. };
  15731. /**
  15732. * Update a raw cube texture
  15733. * @param texture defines the texture to udpdate
  15734. * @param data defines the data to store
  15735. * @param format defines the data format
  15736. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15737. * @param invertY defines if data must be stored with Y axis inverted
  15738. * @param compression defines the compression used (null by default)
  15739. * @param level defines which level of the texture to update
  15740. */
  15741. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15742. if (compression === void 0) { compression = null; }
  15743. if (level === void 0) { level = 0; }
  15744. texture._bufferViewArray = data;
  15745. texture.format = format;
  15746. texture.type = type;
  15747. texture.invertY = invertY;
  15748. texture._compression = compression;
  15749. var gl = this._gl;
  15750. var textureType = this._getWebGLTextureType(type);
  15751. var internalFormat = this._getInternalFormat(format);
  15752. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15753. var needConversion = false;
  15754. if (internalFormat === gl.RGB) {
  15755. internalFormat = gl.RGBA;
  15756. needConversion = true;
  15757. }
  15758. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15759. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15760. if (texture.width % 4 !== 0) {
  15761. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15762. }
  15763. // Data are known to be in +X +Y +Z -X -Y -Z
  15764. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15765. var faceData = data[faceIndex];
  15766. if (compression) {
  15767. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15768. }
  15769. else {
  15770. if (needConversion) {
  15771. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15772. }
  15773. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15774. }
  15775. }
  15776. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15777. if (isPot && texture.generateMipMaps && level === 0) {
  15778. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15779. }
  15780. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15781. // this.resetTextureCache();
  15782. texture.isReady = true;
  15783. };
  15784. /**
  15785. * Creates a new raw cube texture
  15786. * @param data defines the array of data to use to create each face
  15787. * @param size defines the size of the textures
  15788. * @param format defines the format of the data
  15789. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15790. * @param generateMipMaps defines if the engine should generate the mip levels
  15791. * @param invertY defines if data must be stored with Y axis inverted
  15792. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15793. * @param compression defines the compression used (null by default)
  15794. * @returns the cube texture as an InternalTexture
  15795. */
  15796. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15797. if (compression === void 0) { compression = null; }
  15798. var gl = this._gl;
  15799. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15800. texture.isCube = true;
  15801. texture.format = format;
  15802. texture.type = type;
  15803. if (!this._doNotHandleContextLost) {
  15804. texture._bufferViewArray = data;
  15805. }
  15806. var textureType = this._getWebGLTextureType(type);
  15807. var internalFormat = this._getInternalFormat(format);
  15808. if (internalFormat === gl.RGB) {
  15809. internalFormat = gl.RGBA;
  15810. }
  15811. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15812. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15813. generateMipMaps = false;
  15814. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15815. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15816. }
  15817. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15818. generateMipMaps = false;
  15819. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15820. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15821. }
  15822. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15823. generateMipMaps = false;
  15824. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15825. }
  15826. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15827. generateMipMaps = false;
  15828. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15829. }
  15830. var width = size;
  15831. var height = width;
  15832. texture.width = width;
  15833. texture.height = height;
  15834. // Double check on POT to generate Mips.
  15835. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15836. if (!isPot) {
  15837. generateMipMaps = false;
  15838. }
  15839. // Upload data if needed. The texture won't be ready until then.
  15840. if (data) {
  15841. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15842. }
  15843. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15844. // Filters
  15845. if (data && generateMipMaps) {
  15846. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15847. }
  15848. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15853. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15854. texture.generateMipMaps = generateMipMaps;
  15855. return texture;
  15856. };
  15857. /**
  15858. * Creates a new raw cube texture from a specified url
  15859. * @param url defines the url where the data is located
  15860. * @param scene defines the current scene
  15861. * @param size defines the size of the textures
  15862. * @param format defines the format of the data
  15863. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15864. * @param noMipmap defines if the engine should avoid generating the mip levels
  15865. * @param callback defines a callback used to extract texture data from loaded data
  15866. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15867. * @param onLoad defines a callback called when texture is loaded
  15868. * @param onError defines a callback called if there is an error
  15869. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15870. * @param invertY defines if data must be stored with Y axis inverted
  15871. * @returns the cube texture as an InternalTexture
  15872. */
  15873. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15874. var _this = this;
  15875. if (onLoad === void 0) { onLoad = null; }
  15876. if (onError === void 0) { onError = null; }
  15877. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15878. if (invertY === void 0) { invertY = false; }
  15879. var gl = this._gl;
  15880. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15881. scene._addPendingData(texture);
  15882. texture.url = url;
  15883. this._internalTexturesCache.push(texture);
  15884. var onerror = function (request, exception) {
  15885. scene._removePendingData(texture);
  15886. if (onError && request) {
  15887. onError(request.status + " " + request.statusText, exception);
  15888. }
  15889. };
  15890. var internalCallback = function (data) {
  15891. var width = texture.width;
  15892. var faceDataArrays = callback(data);
  15893. if (!faceDataArrays) {
  15894. return;
  15895. }
  15896. if (mipmapGenerator) {
  15897. var textureType = _this._getWebGLTextureType(type);
  15898. var internalFormat = _this._getInternalFormat(format);
  15899. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15900. var needConversion = false;
  15901. if (internalFormat === gl.RGB) {
  15902. internalFormat = gl.RGBA;
  15903. needConversion = true;
  15904. }
  15905. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15906. _this._unpackFlipY(false);
  15907. var mipData = mipmapGenerator(faceDataArrays);
  15908. for (var level = 0; level < mipData.length; level++) {
  15909. var mipSize = width >> level;
  15910. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15911. var mipFaceData = mipData[level][faceIndex];
  15912. if (needConversion) {
  15913. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15914. }
  15915. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15916. }
  15917. }
  15918. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15919. }
  15920. else {
  15921. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15922. }
  15923. texture.isReady = true;
  15924. // this.resetTextureCache();
  15925. scene._removePendingData(texture);
  15926. if (onLoad) {
  15927. onLoad();
  15928. }
  15929. };
  15930. this._loadFile(url, function (data) {
  15931. internalCallback(data);
  15932. }, undefined, scene.database, true, onerror);
  15933. return texture;
  15934. };
  15935. ;
  15936. /**
  15937. * Update a raw 3D texture
  15938. * @param texture defines the texture to update
  15939. * @param data defines the data to store
  15940. * @param format defines the data format
  15941. * @param invertY defines if data must be stored with Y axis inverted
  15942. * @param compression defines the used compression (can be null)
  15943. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15944. */
  15945. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15946. if (compression === void 0) { compression = null; }
  15947. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15948. var internalType = this._getWebGLTextureType(textureType);
  15949. var internalFormat = this._getInternalFormat(format);
  15950. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15951. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15952. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15953. if (!this._doNotHandleContextLost) {
  15954. texture._bufferView = data;
  15955. texture.format = format;
  15956. texture.invertY = invertY;
  15957. texture._compression = compression;
  15958. }
  15959. if (texture.width % 4 !== 0) {
  15960. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15961. }
  15962. if (compression && data) {
  15963. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15964. }
  15965. else {
  15966. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15967. }
  15968. if (texture.generateMipMaps) {
  15969. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15970. }
  15971. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15972. // this.resetTextureCache();
  15973. texture.isReady = true;
  15974. };
  15975. /**
  15976. * Creates a new raw 3D texture
  15977. * @param data defines the data used to create the texture
  15978. * @param width defines the width of the texture
  15979. * @param height defines the height of the texture
  15980. * @param depth defines the depth of the texture
  15981. * @param format defines the format of the texture
  15982. * @param generateMipMaps defines if the engine must generate mip levels
  15983. * @param invertY defines if data must be stored with Y axis inverted
  15984. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15985. * @param compression defines the compressed used (can be null)
  15986. * @param textureType defines the compressed used (can be null)
  15987. * @returns a new raw 3D texture (stored in an InternalTexture)
  15988. */
  15989. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15990. if (compression === void 0) { compression = null; }
  15991. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15992. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15993. texture.baseWidth = width;
  15994. texture.baseHeight = height;
  15995. texture.baseDepth = depth;
  15996. texture.width = width;
  15997. texture.height = height;
  15998. texture.depth = depth;
  15999. texture.format = format;
  16000. texture.type = textureType;
  16001. texture.generateMipMaps = generateMipMaps;
  16002. texture.samplingMode = samplingMode;
  16003. texture.is3D = true;
  16004. if (!this._doNotHandleContextLost) {
  16005. texture._bufferView = data;
  16006. }
  16007. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16008. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16009. // Filters
  16010. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16011. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16012. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16013. if (generateMipMaps) {
  16014. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16015. }
  16016. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16017. this._internalTexturesCache.push(texture);
  16018. return texture;
  16019. };
  16020. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16021. var gl = this._gl;
  16022. if (!gl) {
  16023. return;
  16024. }
  16025. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16026. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16027. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16028. if (!noMipmap && !isCompressed) {
  16029. gl.generateMipmap(gl.TEXTURE_2D);
  16030. }
  16031. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16032. // this.resetTextureCache();
  16033. if (scene) {
  16034. scene._removePendingData(texture);
  16035. }
  16036. texture.onLoadedObservable.notifyObservers(texture);
  16037. texture.onLoadedObservable.clear();
  16038. };
  16039. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16040. var _this = this;
  16041. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16042. var maxTextureSize = this.getCaps().maxTextureSize;
  16043. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16044. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16045. var gl = this._gl;
  16046. if (!gl) {
  16047. return;
  16048. }
  16049. if (!texture._webGLTexture) {
  16050. // this.resetTextureCache();
  16051. if (scene) {
  16052. scene._removePendingData(texture);
  16053. }
  16054. return;
  16055. }
  16056. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16057. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16058. texture.baseWidth = width;
  16059. texture.baseHeight = height;
  16060. texture.width = potWidth;
  16061. texture.height = potHeight;
  16062. texture.isReady = true;
  16063. if (processFunction(potWidth, potHeight, function () {
  16064. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16065. })) {
  16066. // Returning as texture needs extra async steps
  16067. return;
  16068. }
  16069. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16070. };
  16071. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16072. // Create new RGBA data container.
  16073. var rgbaData;
  16074. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16075. rgbaData = new Float32Array(width * height * 4);
  16076. }
  16077. else {
  16078. rgbaData = new Uint32Array(width * height * 4);
  16079. }
  16080. // Convert each pixel.
  16081. for (var x = 0; x < width; x++) {
  16082. for (var y = 0; y < height; y++) {
  16083. var index = (y * width + x) * 3;
  16084. var newIndex = (y * width + x) * 4;
  16085. // Map Old Value to new value.
  16086. rgbaData[newIndex + 0] = rgbData[index + 0];
  16087. rgbaData[newIndex + 1] = rgbData[index + 1];
  16088. rgbaData[newIndex + 2] = rgbData[index + 2];
  16089. // Add fully opaque alpha channel.
  16090. rgbaData[newIndex + 3] = 1;
  16091. }
  16092. }
  16093. return rgbaData;
  16094. };
  16095. /** @hidden */
  16096. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16097. var gl = this._gl;
  16098. if (texture._framebuffer) {
  16099. gl.deleteFramebuffer(texture._framebuffer);
  16100. texture._framebuffer = null;
  16101. }
  16102. if (texture._depthStencilBuffer) {
  16103. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16104. texture._depthStencilBuffer = null;
  16105. }
  16106. if (texture._MSAAFramebuffer) {
  16107. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16108. texture._MSAAFramebuffer = null;
  16109. }
  16110. if (texture._MSAARenderBuffer) {
  16111. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16112. texture._MSAARenderBuffer = null;
  16113. }
  16114. };
  16115. /** @hidden */
  16116. Engine.prototype._releaseTexture = function (texture) {
  16117. var gl = this._gl;
  16118. this._releaseFramebufferObjects(texture);
  16119. gl.deleteTexture(texture._webGLTexture);
  16120. // Unbind channels
  16121. this.unbindAllTextures();
  16122. var index = this._internalTexturesCache.indexOf(texture);
  16123. if (index !== -1) {
  16124. this._internalTexturesCache.splice(index, 1);
  16125. }
  16126. // Integrated fixed lod samplers.
  16127. if (texture._lodTextureHigh) {
  16128. texture._lodTextureHigh.dispose();
  16129. }
  16130. if (texture._lodTextureMid) {
  16131. texture._lodTextureMid.dispose();
  16132. }
  16133. if (texture._lodTextureLow) {
  16134. texture._lodTextureLow.dispose();
  16135. }
  16136. // Set output texture of post process to null if the texture has been released/disposed
  16137. this.scenes.forEach(function (scene) {
  16138. scene.postProcesses.forEach(function (postProcess) {
  16139. if (postProcess._outputTexture == texture) {
  16140. postProcess._outputTexture = null;
  16141. }
  16142. });
  16143. scene.cameras.forEach(function (camera) {
  16144. camera._postProcesses.forEach(function (postProcess) {
  16145. if (postProcess) {
  16146. if (postProcess._outputTexture == texture) {
  16147. postProcess._outputTexture = null;
  16148. }
  16149. }
  16150. });
  16151. });
  16152. });
  16153. };
  16154. Engine.prototype.setProgram = function (program) {
  16155. if (this._currentProgram !== program) {
  16156. this._gl.useProgram(program);
  16157. this._currentProgram = program;
  16158. }
  16159. };
  16160. /**
  16161. * Binds an effect to the webGL context
  16162. * @param effect defines the effect to bind
  16163. */
  16164. Engine.prototype.bindSamplers = function (effect) {
  16165. this.setProgram(effect.getProgram());
  16166. var samplers = effect.getSamplers();
  16167. for (var index = 0; index < samplers.length; index++) {
  16168. var uniform = effect.getUniform(samplers[index]);
  16169. if (uniform) {
  16170. this._boundUniforms[index] = uniform;
  16171. }
  16172. }
  16173. this._currentEffect = null;
  16174. };
  16175. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16176. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16177. return;
  16178. }
  16179. // Remove
  16180. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16181. // Bind last to it
  16182. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16183. // Bind to dummy
  16184. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16185. };
  16186. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16187. if (!internalTexture) {
  16188. return -1;
  16189. }
  16190. internalTexture._initialSlot = channel;
  16191. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16192. if (channel !== internalTexture._designatedSlot) {
  16193. this._textureCollisions.addCount(1, false);
  16194. }
  16195. }
  16196. else {
  16197. if (channel !== internalTexture._designatedSlot) {
  16198. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16199. return internalTexture._designatedSlot;
  16200. }
  16201. else {
  16202. // No slot for this texture, let's pick a new one (if we find a free slot)
  16203. if (this._nextFreeTextureSlots.length) {
  16204. return this._nextFreeTextureSlots[0];
  16205. }
  16206. // We need to recycle the oldest bound texture, sorry.
  16207. this._textureCollisions.addCount(1, false);
  16208. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16209. }
  16210. }
  16211. }
  16212. return channel;
  16213. };
  16214. Engine.prototype._linkTrackers = function (previous, next) {
  16215. previous.next = next;
  16216. next.previous = previous;
  16217. };
  16218. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16219. var currentSlot = internalTexture._designatedSlot;
  16220. if (currentSlot === -1) {
  16221. return -1;
  16222. }
  16223. internalTexture._designatedSlot = -1;
  16224. if (this.disableTextureBindingOptimization) {
  16225. return -1;
  16226. }
  16227. // Remove from bound list
  16228. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16229. // Free the slot
  16230. this._boundTexturesCache[currentSlot] = null;
  16231. this._nextFreeTextureSlots.push(currentSlot);
  16232. return currentSlot;
  16233. };
  16234. Engine.prototype._activateCurrentTexture = function () {
  16235. if (this._currentTextureChannel !== this._activeChannel) {
  16236. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16237. this._currentTextureChannel = this._activeChannel;
  16238. }
  16239. };
  16240. /** @hidden */
  16241. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16242. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16243. if (force === void 0) { force = false; }
  16244. var wasPreviouslyBound = false;
  16245. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16246. this._activeChannel = texture._designatedSlot;
  16247. }
  16248. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16249. var isTextureForRendering = texture && texture._initialSlot > -1;
  16250. if (currentTextureBound !== texture || force) {
  16251. if (currentTextureBound) {
  16252. this._removeDesignatedSlot(currentTextureBound);
  16253. }
  16254. this._activateCurrentTexture();
  16255. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16256. this._boundTexturesCache[this._activeChannel] = texture;
  16257. if (texture) {
  16258. if (!this.disableTextureBindingOptimization) {
  16259. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16260. if (slotIndex > -1) {
  16261. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16262. }
  16263. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16264. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16265. }
  16266. texture._designatedSlot = this._activeChannel;
  16267. }
  16268. }
  16269. else if (forTextureDataUpdate) {
  16270. wasPreviouslyBound = true;
  16271. this._activateCurrentTexture();
  16272. }
  16273. if (isTextureForRendering && !forTextureDataUpdate) {
  16274. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16275. }
  16276. return wasPreviouslyBound;
  16277. };
  16278. /** @hidden */
  16279. Engine.prototype._bindTexture = function (channel, texture) {
  16280. if (channel < 0) {
  16281. return;
  16282. }
  16283. if (texture) {
  16284. channel = this._getCorrectTextureChannel(channel, texture);
  16285. }
  16286. this._activeChannel = channel;
  16287. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16288. };
  16289. /**
  16290. * Sets a texture to the webGL context from a postprocess
  16291. * @param channel defines the channel to use
  16292. * @param postProcess defines the source postprocess
  16293. */
  16294. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16295. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16296. };
  16297. /**
  16298. * Binds the output of the passed in post process to the texture channel specified
  16299. * @param channel The channel the texture should be bound to
  16300. * @param postProcess The post process which's output should be bound
  16301. */
  16302. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16303. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16304. };
  16305. /**
  16306. * Unbind all textures from the webGL context
  16307. */
  16308. Engine.prototype.unbindAllTextures = function () {
  16309. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16310. this._activeChannel = channel;
  16311. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16312. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16313. if (this.webGLVersion > 1) {
  16314. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16315. }
  16316. }
  16317. };
  16318. /**
  16319. * Sets a texture to the according uniform.
  16320. * @param channel The texture channel
  16321. * @param uniform The uniform to set
  16322. * @param texture The texture to apply
  16323. */
  16324. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16325. if (channel < 0) {
  16326. return;
  16327. }
  16328. if (uniform) {
  16329. this._boundUniforms[channel] = uniform;
  16330. }
  16331. this._setTexture(channel, texture);
  16332. };
  16333. /**
  16334. * Sets a depth stencil texture from a render target to the according uniform.
  16335. * @param channel The texture channel
  16336. * @param uniform The uniform to set
  16337. * @param texture The render target texture containing the depth stencil texture to apply
  16338. */
  16339. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16340. if (channel < 0) {
  16341. return;
  16342. }
  16343. if (uniform) {
  16344. this._boundUniforms[channel] = uniform;
  16345. }
  16346. if (!texture || !texture.depthStencilTexture) {
  16347. this._setTexture(channel, null);
  16348. }
  16349. else {
  16350. this._setTexture(channel, texture, false, true);
  16351. }
  16352. };
  16353. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16354. var uniform = this._boundUniforms[sourceSlot];
  16355. if (uniform._currentState === destination) {
  16356. return;
  16357. }
  16358. this._gl.uniform1i(uniform, destination);
  16359. uniform._currentState = destination;
  16360. };
  16361. Engine.prototype._getTextureWrapMode = function (mode) {
  16362. switch (mode) {
  16363. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16364. return this._gl.REPEAT;
  16365. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16366. return this._gl.CLAMP_TO_EDGE;
  16367. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16368. return this._gl.MIRRORED_REPEAT;
  16369. }
  16370. return this._gl.REPEAT;
  16371. };
  16372. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16373. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16374. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16375. // Not ready?
  16376. if (!texture) {
  16377. if (this._boundTexturesCache[channel] != null) {
  16378. this._activeChannel = channel;
  16379. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16380. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16381. if (this.webGLVersion > 1) {
  16382. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16383. }
  16384. }
  16385. return false;
  16386. }
  16387. // Video
  16388. if (texture.video) {
  16389. this._activeChannel = channel;
  16390. texture.update();
  16391. }
  16392. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16393. texture.delayLoad();
  16394. return false;
  16395. }
  16396. var internalTexture;
  16397. if (depthStencilTexture) {
  16398. internalTexture = texture.depthStencilTexture;
  16399. }
  16400. else if (texture.isReady()) {
  16401. internalTexture = texture.getInternalTexture();
  16402. }
  16403. else if (texture.isCube) {
  16404. internalTexture = this.emptyCubeTexture;
  16405. }
  16406. else if (texture.is3D) {
  16407. internalTexture = this.emptyTexture3D;
  16408. }
  16409. else {
  16410. internalTexture = this.emptyTexture;
  16411. }
  16412. if (!isPartOfTextureArray) {
  16413. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16414. }
  16415. var needToBind = true;
  16416. if (this._boundTexturesCache[channel] === internalTexture) {
  16417. this._moveBoundTextureOnTop(internalTexture);
  16418. if (!isPartOfTextureArray) {
  16419. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16420. }
  16421. needToBind = false;
  16422. }
  16423. this._activeChannel = channel;
  16424. if (internalTexture && internalTexture.is3D) {
  16425. if (needToBind) {
  16426. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16427. }
  16428. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16429. internalTexture._cachedWrapU = texture.wrapU;
  16430. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16431. }
  16432. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16433. internalTexture._cachedWrapV = texture.wrapV;
  16434. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16435. }
  16436. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16437. internalTexture._cachedWrapR = texture.wrapR;
  16438. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16439. }
  16440. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16441. }
  16442. else if (internalTexture && internalTexture.isCube) {
  16443. if (needToBind) {
  16444. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16445. }
  16446. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16447. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16448. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16449. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16450. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16451. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16452. }
  16453. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16454. }
  16455. else {
  16456. if (needToBind) {
  16457. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16458. }
  16459. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16460. internalTexture._cachedWrapU = texture.wrapU;
  16461. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16462. }
  16463. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16464. internalTexture._cachedWrapV = texture.wrapV;
  16465. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16466. }
  16467. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16468. }
  16469. return true;
  16470. };
  16471. /**
  16472. * Sets an array of texture to the webGL context
  16473. * @param channel defines the channel where the texture array must be set
  16474. * @param uniform defines the associated uniform location
  16475. * @param textures defines the array of textures to bind
  16476. */
  16477. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16478. if (channel < 0 || !uniform) {
  16479. return;
  16480. }
  16481. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16482. this._textureUnits = new Int32Array(textures.length);
  16483. }
  16484. for (var i = 0; i < textures.length; i++) {
  16485. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16486. }
  16487. this._gl.uniform1iv(uniform, this._textureUnits);
  16488. for (var index = 0; index < textures.length; index++) {
  16489. this._setTexture(this._textureUnits[index], textures[index], true);
  16490. }
  16491. };
  16492. /** @hidden */
  16493. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16494. var internalTexture = texture.getInternalTexture();
  16495. if (!internalTexture) {
  16496. return;
  16497. }
  16498. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16499. var value = texture.anisotropicFilteringLevel;
  16500. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16501. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16502. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16503. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16504. }
  16505. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16506. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16507. internalTexture._cachedAnisotropicFilteringLevel = value;
  16508. }
  16509. };
  16510. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16511. this._bindTextureDirectly(target, texture, true, true);
  16512. this._gl.texParameterf(target, parameter, value);
  16513. };
  16514. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16515. if (texture) {
  16516. this._bindTextureDirectly(target, texture, true, true);
  16517. }
  16518. this._gl.texParameteri(target, parameter, value);
  16519. };
  16520. /**
  16521. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16522. * @param x defines the x coordinate of the rectangle where pixels must be read
  16523. * @param y defines the y coordinate of the rectangle where pixels must be read
  16524. * @param width defines the width of the rectangle where pixels must be read
  16525. * @param height defines the height of the rectangle where pixels must be read
  16526. * @returns a Uint8Array containing RGBA colors
  16527. */
  16528. Engine.prototype.readPixels = function (x, y, width, height) {
  16529. var data = new Uint8Array(height * width * 4);
  16530. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16531. return data;
  16532. };
  16533. /**
  16534. * Add an externaly attached data from its key.
  16535. * This method call will fail and return false, if such key already exists.
  16536. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16537. * @param key the unique key that identifies the data
  16538. * @param data the data object to associate to the key for this Engine instance
  16539. * @return true if no such key were already present and the data was added successfully, false otherwise
  16540. */
  16541. Engine.prototype.addExternalData = function (key, data) {
  16542. if (!this._externalData) {
  16543. this._externalData = new BABYLON.StringDictionary();
  16544. }
  16545. return this._externalData.add(key, data);
  16546. };
  16547. /**
  16548. * Get an externaly attached data from its key
  16549. * @param key the unique key that identifies the data
  16550. * @return the associated data, if present (can be null), or undefined if not present
  16551. */
  16552. Engine.prototype.getExternalData = function (key) {
  16553. if (!this._externalData) {
  16554. this._externalData = new BABYLON.StringDictionary();
  16555. }
  16556. return this._externalData.get(key);
  16557. };
  16558. /**
  16559. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16560. * @param key the unique key that identifies the data
  16561. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16562. * @return the associated data, can be null if the factory returned null.
  16563. */
  16564. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16565. if (!this._externalData) {
  16566. this._externalData = new BABYLON.StringDictionary();
  16567. }
  16568. return this._externalData.getOrAddWithFactory(key, factory);
  16569. };
  16570. /**
  16571. * Remove an externaly attached data from the Engine instance
  16572. * @param key the unique key that identifies the data
  16573. * @return true if the data was successfully removed, false if it doesn't exist
  16574. */
  16575. Engine.prototype.removeExternalData = function (key) {
  16576. if (!this._externalData) {
  16577. this._externalData = new BABYLON.StringDictionary();
  16578. }
  16579. return this._externalData.remove(key);
  16580. };
  16581. /**
  16582. * Unbind all vertex attributes from the webGL context
  16583. */
  16584. Engine.prototype.unbindAllAttributes = function () {
  16585. if (this._mustWipeVertexAttributes) {
  16586. this._mustWipeVertexAttributes = false;
  16587. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16588. this._gl.disableVertexAttribArray(i);
  16589. this._vertexAttribArraysEnabled[i] = false;
  16590. this._currentBufferPointers[i].active = false;
  16591. }
  16592. return;
  16593. }
  16594. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16595. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16596. continue;
  16597. }
  16598. this._gl.disableVertexAttribArray(i);
  16599. this._vertexAttribArraysEnabled[i] = false;
  16600. this._currentBufferPointers[i].active = false;
  16601. }
  16602. };
  16603. /**
  16604. * 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
  16605. */
  16606. Engine.prototype.releaseEffects = function () {
  16607. for (var name in this._compiledEffects) {
  16608. this._deleteProgram(this._compiledEffects[name]._program);
  16609. }
  16610. this._compiledEffects = {};
  16611. };
  16612. /**
  16613. * Dispose and release all associated resources
  16614. */
  16615. Engine.prototype.dispose = function () {
  16616. this.hideLoadingUI();
  16617. this.stopRenderLoop();
  16618. // Release postProcesses
  16619. while (this.postProcesses.length) {
  16620. this.postProcesses[0].dispose();
  16621. }
  16622. // Empty texture
  16623. if (this._emptyTexture) {
  16624. this._releaseTexture(this._emptyTexture);
  16625. this._emptyTexture = null;
  16626. }
  16627. if (this._emptyCubeTexture) {
  16628. this._releaseTexture(this._emptyCubeTexture);
  16629. this._emptyCubeTexture = null;
  16630. }
  16631. // Rescale PP
  16632. if (this._rescalePostProcess) {
  16633. this._rescalePostProcess.dispose();
  16634. }
  16635. // Release scenes
  16636. while (this.scenes.length) {
  16637. this.scenes[0].dispose();
  16638. }
  16639. // Release audio engine
  16640. if (Engine.audioEngine) {
  16641. Engine.audioEngine.dispose();
  16642. }
  16643. // Release effects
  16644. this.releaseEffects();
  16645. // Unbind
  16646. this.unbindAllAttributes();
  16647. this._boundUniforms = [];
  16648. if (this._dummyFramebuffer) {
  16649. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16650. }
  16651. //WebVR
  16652. this.disableVR();
  16653. // Events
  16654. if (BABYLON.Tools.IsWindowObjectExist()) {
  16655. window.removeEventListener("blur", this._onBlur);
  16656. window.removeEventListener("focus", this._onFocus);
  16657. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16658. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16659. if (this._renderingCanvas) {
  16660. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16661. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16662. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16663. if (!this._doNotHandleContextLost) {
  16664. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16665. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16666. }
  16667. }
  16668. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16669. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16670. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16671. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16672. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16673. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16674. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16675. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16676. if (this._onVrDisplayConnect) {
  16677. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16678. if (this._onVrDisplayDisconnect) {
  16679. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16680. }
  16681. if (this._onVrDisplayPresentChange) {
  16682. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16683. }
  16684. this._onVrDisplayConnect = null;
  16685. this._onVrDisplayDisconnect = null;
  16686. }
  16687. }
  16688. // Remove from Instances
  16689. var index = Engine.Instances.indexOf(this);
  16690. if (index >= 0) {
  16691. Engine.Instances.splice(index, 1);
  16692. }
  16693. this._workingCanvas = null;
  16694. this._workingContext = null;
  16695. this._currentBufferPointers = [];
  16696. this._renderingCanvas = null;
  16697. this._currentProgram = null;
  16698. this._bindedRenderFunction = null;
  16699. this.onResizeObservable.clear();
  16700. this.onCanvasBlurObservable.clear();
  16701. this.onCanvasFocusObservable.clear();
  16702. this.onCanvasPointerOutObservable.clear();
  16703. this.onBeginFrameObservable.clear();
  16704. this.onEndFrameObservable.clear();
  16705. BABYLON.Effect.ResetCache();
  16706. // Abort active requests
  16707. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16708. var request = _a[_i];
  16709. request.abort();
  16710. }
  16711. };
  16712. // Loading screen
  16713. /**
  16714. * Display the loading screen
  16715. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16716. */
  16717. Engine.prototype.displayLoadingUI = function () {
  16718. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16719. return;
  16720. }
  16721. var loadingScreen = this.loadingScreen;
  16722. if (loadingScreen) {
  16723. loadingScreen.displayLoadingUI();
  16724. }
  16725. };
  16726. /**
  16727. * Hide the loading screen
  16728. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16729. */
  16730. Engine.prototype.hideLoadingUI = function () {
  16731. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16732. return;
  16733. }
  16734. var loadingScreen = this.loadingScreen;
  16735. if (loadingScreen) {
  16736. loadingScreen.hideLoadingUI();
  16737. }
  16738. };
  16739. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16740. /**
  16741. * Gets the current loading screen object
  16742. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16743. */
  16744. get: function () {
  16745. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16746. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16747. return this._loadingScreen;
  16748. },
  16749. /**
  16750. * Sets the current loading screen object
  16751. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16752. */
  16753. set: function (loadingScreen) {
  16754. this._loadingScreen = loadingScreen;
  16755. },
  16756. enumerable: true,
  16757. configurable: true
  16758. });
  16759. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16760. /**
  16761. * Sets the current loading screen text
  16762. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16763. */
  16764. set: function (text) {
  16765. this.loadingScreen.loadingUIText = text;
  16766. },
  16767. enumerable: true,
  16768. configurable: true
  16769. });
  16770. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16771. /**
  16772. * Sets the current loading screen background color
  16773. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16774. */
  16775. set: function (color) {
  16776. this.loadingScreen.loadingUIBackgroundColor = color;
  16777. },
  16778. enumerable: true,
  16779. configurable: true
  16780. });
  16781. /**
  16782. * Attach a new callback raised when context lost event is fired
  16783. * @param callback defines the callback to call
  16784. */
  16785. Engine.prototype.attachContextLostEvent = function (callback) {
  16786. if (this._renderingCanvas) {
  16787. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16788. }
  16789. };
  16790. /**
  16791. * Attach a new callback raised when context restored event is fired
  16792. * @param callback defines the callback to call
  16793. */
  16794. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16795. if (this._renderingCanvas) {
  16796. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16797. }
  16798. };
  16799. /**
  16800. * Gets the source code of the vertex shader associated with a specific webGL program
  16801. * @param program defines the program to use
  16802. * @returns a string containing the source code of the vertex shader associated with the program
  16803. */
  16804. Engine.prototype.getVertexShaderSource = function (program) {
  16805. var shaders = this._gl.getAttachedShaders(program);
  16806. if (!shaders) {
  16807. return null;
  16808. }
  16809. return this._gl.getShaderSource(shaders[0]);
  16810. };
  16811. /**
  16812. * Gets the source code of the fragment shader associated with a specific webGL program
  16813. * @param program defines the program to use
  16814. * @returns a string containing the source code of the fragment shader associated with the program
  16815. */
  16816. Engine.prototype.getFragmentShaderSource = function (program) {
  16817. var shaders = this._gl.getAttachedShaders(program);
  16818. if (!shaders) {
  16819. return null;
  16820. }
  16821. return this._gl.getShaderSource(shaders[1]);
  16822. };
  16823. /**
  16824. * Get the current error code of the webGL context
  16825. * @returns the error code
  16826. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16827. */
  16828. Engine.prototype.getError = function () {
  16829. return this._gl.getError();
  16830. };
  16831. // FPS
  16832. /**
  16833. * Gets the current framerate
  16834. * @returns a number representing the framerate
  16835. */
  16836. Engine.prototype.getFps = function () {
  16837. return this._fps;
  16838. };
  16839. /**
  16840. * Gets the time spent between current and previous frame
  16841. * @returns a number representing the delta time in ms
  16842. */
  16843. Engine.prototype.getDeltaTime = function () {
  16844. return this._deltaTime;
  16845. };
  16846. Engine.prototype._measureFps = function () {
  16847. this._performanceMonitor.sampleFrame();
  16848. this._fps = this._performanceMonitor.averageFPS;
  16849. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16850. };
  16851. /** @hidden */
  16852. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16853. if (faceIndex === void 0) { faceIndex = -1; }
  16854. if (level === void 0) { level = 0; }
  16855. var gl = this._gl;
  16856. if (!this._dummyFramebuffer) {
  16857. var dummy = gl.createFramebuffer();
  16858. if (!dummy) {
  16859. throw new Error("Unable to create dummy framebuffer");
  16860. }
  16861. this._dummyFramebuffer = dummy;
  16862. }
  16863. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16864. if (faceIndex > -1) {
  16865. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16866. }
  16867. else {
  16868. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16869. }
  16870. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16871. var buffer;
  16872. switch (readType) {
  16873. case gl.UNSIGNED_BYTE:
  16874. buffer = new Uint8Array(4 * width * height);
  16875. readType = gl.UNSIGNED_BYTE;
  16876. break;
  16877. default:
  16878. buffer = new Float32Array(4 * width * height);
  16879. readType = gl.FLOAT;
  16880. break;
  16881. }
  16882. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16883. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16884. return buffer;
  16885. };
  16886. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16887. if (this._webGLVersion > 1) {
  16888. return this._caps.colorBufferFloat;
  16889. }
  16890. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16891. };
  16892. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16893. if (this._webGLVersion > 1) {
  16894. return this._caps.colorBufferFloat;
  16895. }
  16896. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16897. };
  16898. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16899. Engine.prototype._canRenderToFramebuffer = function (type) {
  16900. var gl = this._gl;
  16901. //clear existing errors
  16902. while (gl.getError() !== gl.NO_ERROR) { }
  16903. var successful = true;
  16904. var texture = gl.createTexture();
  16905. gl.bindTexture(gl.TEXTURE_2D, texture);
  16906. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16907. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16909. var fb = gl.createFramebuffer();
  16910. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16911. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16912. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16913. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16914. successful = successful && (gl.getError() === gl.NO_ERROR);
  16915. //try render by clearing frame buffer's color buffer
  16916. if (successful) {
  16917. gl.clear(gl.COLOR_BUFFER_BIT);
  16918. successful = successful && (gl.getError() === gl.NO_ERROR);
  16919. }
  16920. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16921. if (successful) {
  16922. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16923. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16924. var readFormat = gl.RGBA;
  16925. var readType = gl.UNSIGNED_BYTE;
  16926. var buffer = new Uint8Array(4);
  16927. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16928. successful = successful && (gl.getError() === gl.NO_ERROR);
  16929. }
  16930. //clean up
  16931. gl.deleteTexture(texture);
  16932. gl.deleteFramebuffer(fb);
  16933. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16934. //clear accumulated errors
  16935. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16936. return successful;
  16937. };
  16938. /** @hidden */
  16939. Engine.prototype._getWebGLTextureType = function (type) {
  16940. if (this._webGLVersion === 1) {
  16941. switch (type) {
  16942. case Engine.TEXTURETYPE_FLOAT:
  16943. return this._gl.FLOAT;
  16944. case Engine.TEXTURETYPE_HALF_FLOAT:
  16945. return this._gl.HALF_FLOAT_OES;
  16946. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16947. return this._gl.UNSIGNED_BYTE;
  16948. }
  16949. return this._gl.UNSIGNED_BYTE;
  16950. }
  16951. switch (type) {
  16952. case Engine.TEXTURETYPE_BYTE:
  16953. return this._gl.BYTE;
  16954. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16955. return this._gl.UNSIGNED_BYTE;
  16956. case Engine.TEXTURETYPE_SHORT:
  16957. return this._gl.SHORT;
  16958. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16959. return this._gl.UNSIGNED_SHORT;
  16960. case Engine.TEXTURETYPE_INT:
  16961. return this._gl.INT;
  16962. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16963. return this._gl.UNSIGNED_INT;
  16964. case Engine.TEXTURETYPE_FLOAT:
  16965. return this._gl.FLOAT;
  16966. case Engine.TEXTURETYPE_HALF_FLOAT:
  16967. return this._gl.HALF_FLOAT;
  16968. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16969. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16970. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16971. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16972. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16973. return this._gl.UNSIGNED_SHORT_5_6_5;
  16974. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16975. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16976. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16977. return this._gl.UNSIGNED_INT_24_8;
  16978. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16979. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16980. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16981. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16982. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16983. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16984. }
  16985. return this._gl.UNSIGNED_BYTE;
  16986. };
  16987. ;
  16988. Engine.prototype._getInternalFormat = function (format) {
  16989. var internalFormat = this._gl.RGBA;
  16990. switch (format) {
  16991. case Engine.TEXTUREFORMAT_ALPHA:
  16992. internalFormat = this._gl.ALPHA;
  16993. break;
  16994. case Engine.TEXTUREFORMAT_LUMINANCE:
  16995. internalFormat = this._gl.LUMINANCE;
  16996. break;
  16997. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16998. internalFormat = this._gl.LUMINANCE_ALPHA;
  16999. break;
  17000. case Engine.TEXTUREFORMAT_RED:
  17001. internalFormat = this._gl.RED;
  17002. break;
  17003. case Engine.TEXTUREFORMAT_RG:
  17004. internalFormat = this._gl.RG;
  17005. break;
  17006. case Engine.TEXTUREFORMAT_RGB:
  17007. internalFormat = this._gl.RGB;
  17008. break;
  17009. case Engine.TEXTUREFORMAT_RGBA:
  17010. internalFormat = this._gl.RGBA;
  17011. break;
  17012. }
  17013. if (this._webGLVersion > 1) {
  17014. switch (format) {
  17015. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17016. internalFormat = this._gl.RED_INTEGER;
  17017. break;
  17018. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17019. internalFormat = this._gl.RG_INTEGER;
  17020. break;
  17021. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17022. internalFormat = this._gl.RGB_INTEGER;
  17023. break;
  17024. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17025. internalFormat = this._gl.RGBA_INTEGER;
  17026. break;
  17027. }
  17028. }
  17029. return internalFormat;
  17030. };
  17031. /** @hidden */
  17032. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17033. if (this._webGLVersion === 1) {
  17034. if (format !== undefined) {
  17035. switch (format) {
  17036. case Engine.TEXTUREFORMAT_ALPHA:
  17037. return this._gl.ALPHA;
  17038. case Engine.TEXTUREFORMAT_LUMINANCE:
  17039. return this._gl.LUMINANCE;
  17040. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17041. return this._gl.LUMINANCE_ALPHA;
  17042. }
  17043. }
  17044. return this._gl.RGBA;
  17045. }
  17046. switch (type) {
  17047. case Engine.TEXTURETYPE_BYTE:
  17048. switch (format) {
  17049. case Engine.TEXTUREFORMAT_RED:
  17050. return this._gl.R8_SNORM;
  17051. case Engine.TEXTUREFORMAT_RG:
  17052. return this._gl.RG8_SNORM;
  17053. case Engine.TEXTUREFORMAT_RGB:
  17054. return this._gl.RGB8_SNORM;
  17055. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17056. return this._gl.R8I;
  17057. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17058. return this._gl.RG8I;
  17059. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17060. return this._gl.RGB8I;
  17061. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17062. return this._gl.RGBA8I;
  17063. default:
  17064. return this._gl.RGBA8_SNORM;
  17065. }
  17066. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17067. switch (format) {
  17068. case Engine.TEXTUREFORMAT_RED:
  17069. return this._gl.R8;
  17070. case Engine.TEXTUREFORMAT_RG:
  17071. return this._gl.RG8;
  17072. case Engine.TEXTUREFORMAT_RGB:
  17073. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17074. case Engine.TEXTUREFORMAT_RGBA:
  17075. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17076. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17077. return this._gl.R8UI;
  17078. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17079. return this._gl.RG8UI;
  17080. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17081. return this._gl.RGB8UI;
  17082. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17083. return this._gl.RGBA8UI;
  17084. default:
  17085. return this._gl.RGBA8;
  17086. }
  17087. case Engine.TEXTURETYPE_SHORT:
  17088. switch (format) {
  17089. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17090. return this._gl.R16I;
  17091. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17092. return this._gl.RG16I;
  17093. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17094. return this._gl.RGB16I;
  17095. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17096. return this._gl.RGBA16I;
  17097. default:
  17098. return this._gl.RGBA16I;
  17099. }
  17100. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17101. switch (format) {
  17102. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17103. return this._gl.R16UI;
  17104. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17105. return this._gl.RG16UI;
  17106. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17107. return this._gl.RGB16UI;
  17108. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17109. return this._gl.RGBA16UI;
  17110. default:
  17111. return this._gl.RGBA16UI;
  17112. }
  17113. case Engine.TEXTURETYPE_INT:
  17114. switch (format) {
  17115. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17116. return this._gl.R32I;
  17117. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17118. return this._gl.RG32I;
  17119. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17120. return this._gl.RGB32I;
  17121. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17122. return this._gl.RGBA32I;
  17123. default:
  17124. return this._gl.RGBA32I;
  17125. }
  17126. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17127. switch (format) {
  17128. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17129. return this._gl.R32UI;
  17130. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17131. return this._gl.RG32UI;
  17132. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17133. return this._gl.RGB32UI;
  17134. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17135. return this._gl.RGBA32UI;
  17136. default:
  17137. return this._gl.RGBA32UI;
  17138. }
  17139. case Engine.TEXTURETYPE_FLOAT:
  17140. switch (format) {
  17141. case Engine.TEXTUREFORMAT_RED:
  17142. return this._gl.R32F; // By default. Other possibility is R16F.
  17143. case Engine.TEXTUREFORMAT_RG:
  17144. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17145. case Engine.TEXTUREFORMAT_RGB:
  17146. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17147. case Engine.TEXTUREFORMAT_RGBA:
  17148. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17149. default:
  17150. return this._gl.RGBA32F;
  17151. }
  17152. case Engine.TEXTURETYPE_HALF_FLOAT:
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_RED:
  17155. return this._gl.R16F;
  17156. case Engine.TEXTUREFORMAT_RG:
  17157. return this._gl.RG16F;
  17158. case Engine.TEXTUREFORMAT_RGB:
  17159. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17160. case Engine.TEXTUREFORMAT_RGBA:
  17161. return this._gl.RGBA16F;
  17162. default:
  17163. return this._gl.RGBA16F;
  17164. }
  17165. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17166. return this._gl.RGB565;
  17167. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17168. return this._gl.R11F_G11F_B10F;
  17169. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17170. return this._gl.RGB9_E5;
  17171. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17172. return this._gl.RGBA4;
  17173. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17174. return this._gl.RGB5_A1;
  17175. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17176. switch (format) {
  17177. case Engine.TEXTUREFORMAT_RGBA:
  17178. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17179. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17180. return this._gl.RGB10_A2UI;
  17181. default:
  17182. return this._gl.RGB10_A2;
  17183. }
  17184. }
  17185. return this._gl.RGBA8;
  17186. };
  17187. ;
  17188. /** @hidden */
  17189. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17190. if (type === Engine.TEXTURETYPE_FLOAT) {
  17191. return this._gl.RGBA32F;
  17192. }
  17193. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17194. return this._gl.RGBA16F;
  17195. }
  17196. return this._gl.RGBA8;
  17197. };
  17198. ;
  17199. /** @hidden */
  17200. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17201. var _this = this;
  17202. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17203. this._activeRequests.push(request);
  17204. request.onCompleteObservable.add(function (request) {
  17205. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17206. });
  17207. return request;
  17208. };
  17209. /** @hidden */
  17210. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17211. var _this = this;
  17212. return new Promise(function (resolve, reject) {
  17213. _this._loadFile(url, function (data) {
  17214. resolve(data);
  17215. }, undefined, database, useArrayBuffer, function (request, exception) {
  17216. reject(exception);
  17217. });
  17218. });
  17219. };
  17220. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17221. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17222. var onload = function (data) {
  17223. loadedFiles[index] = data;
  17224. loadedFiles._internalCount++;
  17225. if (loadedFiles._internalCount === 6) {
  17226. onfinish(loadedFiles);
  17227. }
  17228. };
  17229. var onerror = function (request, exception) {
  17230. if (onErrorCallBack && request) {
  17231. onErrorCallBack(request.status + " " + request.statusText, exception);
  17232. }
  17233. };
  17234. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17235. };
  17236. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17237. if (onError === void 0) { onError = null; }
  17238. var loadedFiles = [];
  17239. loadedFiles._internalCount = 0;
  17240. for (var index = 0; index < 6; index++) {
  17241. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17242. }
  17243. };
  17244. // Statics
  17245. /**
  17246. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17247. * @returns true if the engine can be created
  17248. * @ignorenaming
  17249. */
  17250. Engine.isSupported = function () {
  17251. try {
  17252. var tempcanvas = document.createElement("canvas");
  17253. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17254. return gl != null && !!window.WebGLRenderingContext;
  17255. }
  17256. catch (e) {
  17257. return false;
  17258. }
  17259. };
  17260. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17261. Engine.ExceptionList = [
  17262. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17263. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17264. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17265. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17266. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17267. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17268. ];
  17269. /** Gets the list of created engines */
  17270. Engine.Instances = new Array();
  17271. /**
  17272. * Hidden
  17273. */
  17274. Engine._TextureLoaders = [];
  17275. // Const statics
  17276. /** Defines that alpha blending is disabled */
  17277. Engine.ALPHA_DISABLE = 0;
  17278. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17279. Engine.ALPHA_ADD = 1;
  17280. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17281. Engine.ALPHA_COMBINE = 2;
  17282. /** Defines that alpha blending to DEST - SRC * DEST */
  17283. Engine.ALPHA_SUBTRACT = 3;
  17284. /** Defines that alpha blending to SRC * DEST */
  17285. Engine.ALPHA_MULTIPLY = 4;
  17286. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17287. Engine.ALPHA_MAXIMIZED = 5;
  17288. /** Defines that alpha blending to SRC + DEST */
  17289. Engine.ALPHA_ONEONE = 6;
  17290. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17291. Engine.ALPHA_PREMULTIPLIED = 7;
  17292. /**
  17293. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17294. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17295. */
  17296. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17297. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17298. Engine.ALPHA_INTERPOLATE = 9;
  17299. /**
  17300. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17301. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17302. */
  17303. Engine.ALPHA_SCREENMODE = 10;
  17304. /** Defines that the ressource is not delayed*/
  17305. Engine.DELAYLOADSTATE_NONE = 0;
  17306. /** Defines that the ressource was successfully delay loaded */
  17307. Engine.DELAYLOADSTATE_LOADED = 1;
  17308. /** Defines that the ressource is currently delay loading */
  17309. Engine.DELAYLOADSTATE_LOADING = 2;
  17310. /** Defines that the ressource is delayed and has not started loading */
  17311. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17312. // Depht or Stencil test Constants.
  17313. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17314. Engine.NEVER = 0x0200;
  17315. /** 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 */
  17316. Engine.ALWAYS = 0x0207;
  17317. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17318. Engine.LESS = 0x0201;
  17319. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17320. Engine.EQUAL = 0x0202;
  17321. /** 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 */
  17322. Engine.LEQUAL = 0x0203;
  17323. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17324. Engine.GREATER = 0x0204;
  17325. /** 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 */
  17326. Engine.GEQUAL = 0x0206;
  17327. /** 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 */
  17328. Engine.NOTEQUAL = 0x0205;
  17329. // Stencil Actions Constants.
  17330. /** Passed to stencilOperation to specify that stencil value must be kept */
  17331. Engine.KEEP = 0x1E00;
  17332. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17333. Engine.REPLACE = 0x1E01;
  17334. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17335. Engine.INCR = 0x1E02;
  17336. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17337. Engine.DECR = 0x1E03;
  17338. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17339. Engine.INVERT = 0x150A;
  17340. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17341. Engine.INCR_WRAP = 0x8507;
  17342. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17343. Engine.DECR_WRAP = 0x8508;
  17344. /** Texture is not repeating outside of 0..1 UVs */
  17345. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17346. /** Texture is repeating outside of 0..1 UVs */
  17347. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17348. /** Texture is repeating and mirrored */
  17349. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17350. /** ALPHA */
  17351. Engine.TEXTUREFORMAT_ALPHA = 0;
  17352. /** LUMINANCE */
  17353. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17354. /** LUMINANCE_ALPHA */
  17355. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17356. /** RGB */
  17357. Engine.TEXTUREFORMAT_RGB = 4;
  17358. /** RGBA */
  17359. Engine.TEXTUREFORMAT_RGBA = 5;
  17360. /** RED */
  17361. Engine.TEXTUREFORMAT_RED = 6;
  17362. /** RED (2nd reference) */
  17363. Engine.TEXTUREFORMAT_R = 6;
  17364. /** RG */
  17365. Engine.TEXTUREFORMAT_RG = 7;
  17366. /** RED_INTEGER */
  17367. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17368. /** RED_INTEGER (2nd reference) */
  17369. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17370. /** RG_INTEGER */
  17371. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17372. /** RGB_INTEGER */
  17373. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17374. /** RGBA_INTEGER */
  17375. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17376. /** UNSIGNED_BYTE */
  17377. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17378. /** UNSIGNED_BYTE (2nd reference) */
  17379. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17380. /** FLOAT */
  17381. Engine.TEXTURETYPE_FLOAT = 1;
  17382. /** HALF_FLOAT */
  17383. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17384. /** BYTE */
  17385. Engine.TEXTURETYPE_BYTE = 3;
  17386. /** SHORT */
  17387. Engine.TEXTURETYPE_SHORT = 4;
  17388. /** UNSIGNED_SHORT */
  17389. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17390. /** INT */
  17391. Engine.TEXTURETYPE_INT = 6;
  17392. /** UNSIGNED_INT */
  17393. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17394. /** UNSIGNED_SHORT_4_4_4_4 */
  17395. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17396. /** UNSIGNED_SHORT_5_5_5_1 */
  17397. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17398. /** UNSIGNED_SHORT_5_6_5 */
  17399. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17400. /** UNSIGNED_INT_2_10_10_10_REV */
  17401. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17402. /** UNSIGNED_INT_24_8 */
  17403. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17404. /** UNSIGNED_INT_10F_11F_11F_REV */
  17405. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17406. /** UNSIGNED_INT_5_9_9_9_REV */
  17407. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17408. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17409. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17410. /** nearest is mag = nearest and min = nearest and mip = linear */
  17411. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17412. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17413. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17414. /** Trilinear is mag = linear and min = linear and mip = linear */
  17415. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17416. /** nearest is mag = nearest and min = nearest and mip = linear */
  17417. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17418. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17419. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17420. /** Trilinear is mag = linear and min = linear and mip = linear */
  17421. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17422. /** mag = nearest and min = nearest and mip = nearest */
  17423. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17424. /** mag = nearest and min = linear and mip = nearest */
  17425. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17426. /** mag = nearest and min = linear and mip = linear */
  17427. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17428. /** mag = nearest and min = linear and mip = none */
  17429. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17430. /** mag = nearest and min = nearest and mip = none */
  17431. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17432. /** mag = linear and min = nearest and mip = nearest */
  17433. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17434. /** mag = linear and min = nearest and mip = linear */
  17435. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17436. /** mag = linear and min = linear and mip = none */
  17437. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17438. /** mag = linear and min = nearest and mip = none */
  17439. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17440. /** Explicit coordinates mode */
  17441. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17442. /** Spherical coordinates mode */
  17443. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17444. /** Planar coordinates mode */
  17445. Engine.TEXTURE_PLANAR_MODE = 2;
  17446. /** Cubic coordinates mode */
  17447. Engine.TEXTURE_CUBIC_MODE = 3;
  17448. /** Projection coordinates mode */
  17449. Engine.TEXTURE_PROJECTION_MODE = 4;
  17450. /** Skybox coordinates mode */
  17451. Engine.TEXTURE_SKYBOX_MODE = 5;
  17452. /** Inverse Cubic coordinates mode */
  17453. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17454. /** Equirectangular coordinates mode */
  17455. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17456. /** Equirectangular Fixed coordinates mode */
  17457. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17458. /** Equirectangular Fixed Mirrored coordinates mode */
  17459. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17460. // Texture rescaling mode
  17461. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17462. Engine.SCALEMODE_FLOOR = 1;
  17463. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17464. Engine.SCALEMODE_NEAREST = 2;
  17465. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17466. Engine.SCALEMODE_CEILING = 3;
  17467. // Updatable statics so stick with vars here
  17468. /**
  17469. * Gets or sets the epsilon value used by collision engine
  17470. */
  17471. Engine.CollisionsEpsilon = 0.001;
  17472. /**
  17473. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17474. */
  17475. Engine.CodeRepository = "src/";
  17476. /**
  17477. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17478. */
  17479. Engine.ShadersRepository = "src/Shaders/";
  17480. return Engine;
  17481. }());
  17482. BABYLON.Engine = Engine;
  17483. })(BABYLON || (BABYLON = {}));
  17484. //# sourceMappingURL=babylon.engine.js.map
  17485. var BABYLON;
  17486. (function (BABYLON) {
  17487. /**
  17488. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17489. */
  17490. var Node = /** @class */ (function () {
  17491. /**
  17492. * Creates a new Node
  17493. * @param {string} name - the name and id to be given to this node
  17494. * @param {BABYLON.Scene} the scene this node will be added to
  17495. */
  17496. function Node(name, scene) {
  17497. if (scene === void 0) { scene = null; }
  17498. /**
  17499. * Gets or sets a string used to store user defined state for the node
  17500. */
  17501. this.state = "";
  17502. /**
  17503. * Gets or sets an object used to store user defined information for the node
  17504. */
  17505. this.metadata = null;
  17506. /**
  17507. * Gets or sets a boolean used to define if the node must be serialized
  17508. */
  17509. this.doNotSerialize = false;
  17510. /** @hidden */
  17511. this._isDisposed = false;
  17512. /**
  17513. * Gets a list of Animations associated with the node
  17514. */
  17515. this.animations = new Array();
  17516. this._ranges = {};
  17517. this._isEnabled = true;
  17518. this._isReady = true;
  17519. /** @hidden */
  17520. this._currentRenderId = -1;
  17521. this._parentRenderId = -1;
  17522. this._childRenderId = -1;
  17523. this._animationPropertiesOverride = null;
  17524. /**
  17525. * An event triggered when the mesh is disposed
  17526. */
  17527. this.onDisposeObservable = new BABYLON.Observable();
  17528. // Behaviors
  17529. this._behaviors = new Array();
  17530. this.name = name;
  17531. this.id = name;
  17532. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17533. this.uniqueId = this._scene.getUniqueId();
  17534. this._initCache();
  17535. }
  17536. /**
  17537. * Add a new node constructor
  17538. * @param type defines the type name of the node to construct
  17539. * @param constructorFunc defines the constructor function
  17540. */
  17541. Node.AddNodeConstructor = function (type, constructorFunc) {
  17542. this._NodeConstructors[type] = constructorFunc;
  17543. };
  17544. /**
  17545. * Returns a node constructor based on type name
  17546. * @param type defines the type name
  17547. * @param name defines the new node name
  17548. * @param scene defines the hosting scene
  17549. * @param options defines optional options to transmit to constructors
  17550. * @returns the new constructor or null
  17551. */
  17552. Node.Construct = function (type, name, scene, options) {
  17553. var constructorFunc = this._NodeConstructors[type];
  17554. if (!constructorFunc) {
  17555. return null;
  17556. }
  17557. return constructorFunc(name, scene, options);
  17558. };
  17559. /**
  17560. * Gets a boolean indicating if the node has been disposed
  17561. * @returns true if the node was disposed
  17562. */
  17563. Node.prototype.isDisposed = function () {
  17564. return this._isDisposed;
  17565. };
  17566. Object.defineProperty(Node.prototype, "parent", {
  17567. get: function () {
  17568. return this._parentNode;
  17569. },
  17570. /**
  17571. * Gets or sets the parent of the node
  17572. */
  17573. set: function (parent) {
  17574. if (this._parentNode === parent) {
  17575. return;
  17576. }
  17577. // Remove self from list of children of parent
  17578. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17579. var index = this._parentNode._children.indexOf(this);
  17580. if (index !== -1) {
  17581. this._parentNode._children.splice(index, 1);
  17582. }
  17583. }
  17584. // Store new parent
  17585. this._parentNode = parent;
  17586. // Add as child to new parent
  17587. if (this._parentNode) {
  17588. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17589. this._parentNode._children = new Array();
  17590. }
  17591. this._parentNode._children.push(this);
  17592. }
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17598. /**
  17599. * Gets or sets the animation properties override
  17600. */
  17601. get: function () {
  17602. if (!this._animationPropertiesOverride) {
  17603. return this._scene.animationPropertiesOverride;
  17604. }
  17605. return this._animationPropertiesOverride;
  17606. },
  17607. set: function (value) {
  17608. this._animationPropertiesOverride = value;
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. /**
  17614. * Gets a string idenfifying the name of the class
  17615. * @returns "Node" string
  17616. */
  17617. Node.prototype.getClassName = function () {
  17618. return "Node";
  17619. };
  17620. Object.defineProperty(Node.prototype, "onDispose", {
  17621. /**
  17622. * Sets a callback that will be raised when the node will be disposed
  17623. */
  17624. set: function (callback) {
  17625. if (this._onDisposeObserver) {
  17626. this.onDisposeObservable.remove(this._onDisposeObserver);
  17627. }
  17628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Gets the scene of the node
  17635. * @returns a {BABYLON.Scene}
  17636. */
  17637. Node.prototype.getScene = function () {
  17638. return this._scene;
  17639. };
  17640. /**
  17641. * Gets the engine of the node
  17642. * @returns a {BABYLON.Engine}
  17643. */
  17644. Node.prototype.getEngine = function () {
  17645. return this._scene.getEngine();
  17646. };
  17647. /**
  17648. * Attach a behavior to the node
  17649. * @see http://doc.babylonjs.com/features/behaviour
  17650. * @param behavior defines the behavior to attach
  17651. * @returns the current Node
  17652. */
  17653. Node.prototype.addBehavior = function (behavior) {
  17654. var _this = this;
  17655. var index = this._behaviors.indexOf(behavior);
  17656. if (index !== -1) {
  17657. return this;
  17658. }
  17659. behavior.init();
  17660. if (this._scene.isLoading) {
  17661. // We defer the attach when the scene will be loaded
  17662. this._scene.onDataLoadedObservable.addOnce(function () {
  17663. behavior.attach(_this);
  17664. });
  17665. }
  17666. else {
  17667. behavior.attach(this);
  17668. }
  17669. this._behaviors.push(behavior);
  17670. return this;
  17671. };
  17672. /**
  17673. * Remove an attached behavior
  17674. * @see http://doc.babylonjs.com/features/behaviour
  17675. * @param behavior defines the behavior to attach
  17676. * @returns the current Node
  17677. */
  17678. Node.prototype.removeBehavior = function (behavior) {
  17679. var index = this._behaviors.indexOf(behavior);
  17680. if (index === -1) {
  17681. return this;
  17682. }
  17683. this._behaviors[index].detach();
  17684. this._behaviors.splice(index, 1);
  17685. return this;
  17686. };
  17687. Object.defineProperty(Node.prototype, "behaviors", {
  17688. /**
  17689. * Gets the list of attached behaviors
  17690. * @see http://doc.babylonjs.com/features/behaviour
  17691. */
  17692. get: function () {
  17693. return this._behaviors;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. /**
  17699. * Gets an attached behavior by name
  17700. * @param name defines the name of the behavior to look for
  17701. * @see http://doc.babylonjs.com/features/behaviour
  17702. * @returns null if behavior was not found else the requested behavior
  17703. */
  17704. Node.prototype.getBehaviorByName = function (name) {
  17705. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17706. var behavior = _a[_i];
  17707. if (behavior.name === name) {
  17708. return behavior;
  17709. }
  17710. }
  17711. return null;
  17712. };
  17713. /**
  17714. * Returns the world matrix of the node
  17715. * @returns a matrix containing the node's world matrix
  17716. */
  17717. Node.prototype.getWorldMatrix = function () {
  17718. return BABYLON.Matrix.Identity();
  17719. };
  17720. /** @hidden */
  17721. Node.prototype._getWorldMatrixDeterminant = function () {
  17722. return 1;
  17723. };
  17724. // override it in derived class if you add new variables to the cache
  17725. // and call the parent class method
  17726. /** @hidden */
  17727. Node.prototype._initCache = function () {
  17728. this._cache = {};
  17729. this._cache.parent = undefined;
  17730. };
  17731. /** @hidden */
  17732. Node.prototype.updateCache = function (force) {
  17733. if (!force && this.isSynchronized())
  17734. return;
  17735. this._cache.parent = this.parent;
  17736. this._updateCache();
  17737. };
  17738. // override it in derived class if you add new variables to the cache
  17739. // and call the parent class method if !ignoreParentClass
  17740. /** @hidden */
  17741. Node.prototype._updateCache = function (ignoreParentClass) {
  17742. };
  17743. // override it in derived class if you add new variables to the cache
  17744. /** @hidden */
  17745. Node.prototype._isSynchronized = function () {
  17746. return true;
  17747. };
  17748. /** @hidden */
  17749. Node.prototype._markSyncedWithParent = function () {
  17750. if (this.parent) {
  17751. this._parentRenderId = this.parent._childRenderId;
  17752. }
  17753. };
  17754. /** @hidden */
  17755. Node.prototype.isSynchronizedWithParent = function () {
  17756. if (!this.parent) {
  17757. return true;
  17758. }
  17759. if (this._parentRenderId !== this.parent._childRenderId) {
  17760. return false;
  17761. }
  17762. return this.parent.isSynchronized();
  17763. };
  17764. /** @hidden */
  17765. Node.prototype.isSynchronized = function (updateCache) {
  17766. var check = this.hasNewParent();
  17767. check = check || !this.isSynchronizedWithParent();
  17768. check = check || !this._isSynchronized();
  17769. if (updateCache)
  17770. this.updateCache(true);
  17771. return !check;
  17772. };
  17773. /** @hidden */
  17774. Node.prototype.hasNewParent = function (update) {
  17775. if (this._cache.parent === this.parent)
  17776. return false;
  17777. if (update)
  17778. this._cache.parent = this.parent;
  17779. return true;
  17780. };
  17781. /**
  17782. * Is this node ready to be used/rendered
  17783. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17784. * @return true if the node is ready
  17785. */
  17786. Node.prototype.isReady = function (completeCheck) {
  17787. if (completeCheck === void 0) { completeCheck = false; }
  17788. return this._isReady;
  17789. };
  17790. /**
  17791. * Is this node enabled?
  17792. * 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
  17793. * @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
  17794. * @return whether this node (and its parent) is enabled
  17795. */
  17796. Node.prototype.isEnabled = function (checkAncestors) {
  17797. if (checkAncestors === void 0) { checkAncestors = true; }
  17798. if (checkAncestors === false) {
  17799. return this._isEnabled;
  17800. }
  17801. if (this._isEnabled === false) {
  17802. return false;
  17803. }
  17804. if (this.parent !== undefined && this.parent !== null) {
  17805. return this.parent.isEnabled(checkAncestors);
  17806. }
  17807. return true;
  17808. };
  17809. /**
  17810. * Set the enabled state of this node
  17811. * @param value defines the new enabled state
  17812. */
  17813. Node.prototype.setEnabled = function (value) {
  17814. this._isEnabled = value;
  17815. };
  17816. /**
  17817. * Is this node a descendant of the given node?
  17818. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17819. * @param ancestor defines the parent node to inspect
  17820. * @returns a boolean indicating if this node is a descendant of the given node
  17821. */
  17822. Node.prototype.isDescendantOf = function (ancestor) {
  17823. if (this.parent) {
  17824. if (this.parent === ancestor) {
  17825. return true;
  17826. }
  17827. return this.parent.isDescendantOf(ancestor);
  17828. }
  17829. return false;
  17830. };
  17831. /** @hidden */
  17832. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17833. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17834. if (!this._children) {
  17835. return;
  17836. }
  17837. for (var index = 0; index < this._children.length; index++) {
  17838. var item = this._children[index];
  17839. if (!predicate || predicate(item)) {
  17840. results.push(item);
  17841. }
  17842. if (!directDescendantsOnly) {
  17843. item._getDescendants(results, false, predicate);
  17844. }
  17845. }
  17846. };
  17847. /**
  17848. * Will return all nodes that have this node as ascendant
  17849. * @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
  17850. * @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
  17851. * @return all children nodes of all types
  17852. */
  17853. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17854. var results = new Array();
  17855. this._getDescendants(results, directDescendantsOnly, predicate);
  17856. return results;
  17857. };
  17858. /**
  17859. * Get all child-meshes of this node
  17860. * @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
  17861. * @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
  17862. * @returns an array of {BABYLON.AbstractMesh}
  17863. */
  17864. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17865. var results = [];
  17866. this._getDescendants(results, directDescendantsOnly, function (node) {
  17867. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17868. });
  17869. return results;
  17870. };
  17871. /**
  17872. * Get all child-transformNodes of this node
  17873. * @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
  17874. * @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
  17875. * @returns an array of {BABYLON.TransformNode}
  17876. */
  17877. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17878. var results = [];
  17879. this._getDescendants(results, directDescendantsOnly, function (node) {
  17880. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17881. });
  17882. return results;
  17883. };
  17884. /**
  17885. * Get all direct children of this node
  17886. * @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
  17887. * @returns an array of {BABYLON.Node}
  17888. */
  17889. Node.prototype.getChildren = function (predicate) {
  17890. return this.getDescendants(true, predicate);
  17891. };
  17892. /** @hidden */
  17893. Node.prototype._setReady = function (state) {
  17894. if (state === this._isReady) {
  17895. return;
  17896. }
  17897. if (!state) {
  17898. this._isReady = false;
  17899. return;
  17900. }
  17901. if (this.onReady) {
  17902. this.onReady(this);
  17903. }
  17904. this._isReady = true;
  17905. };
  17906. /**
  17907. * Get an animation by name
  17908. * @param name defines the name of the animation to look for
  17909. * @returns null if not found else the requested animation
  17910. */
  17911. Node.prototype.getAnimationByName = function (name) {
  17912. for (var i = 0; i < this.animations.length; i++) {
  17913. var animation = this.animations[i];
  17914. if (animation.name === name) {
  17915. return animation;
  17916. }
  17917. }
  17918. return null;
  17919. };
  17920. /**
  17921. * Creates an animation range for this node
  17922. * @param name defines the name of the range
  17923. * @param from defines the starting key
  17924. * @param to defines the end key
  17925. */
  17926. Node.prototype.createAnimationRange = function (name, from, to) {
  17927. // check name not already in use
  17928. if (!this._ranges[name]) {
  17929. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17930. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17931. if (this.animations[i]) {
  17932. this.animations[i].createRange(name, from, to);
  17933. }
  17934. }
  17935. }
  17936. };
  17937. /**
  17938. * Delete a specific animation range
  17939. * @param name defines the name of the range to delete
  17940. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17941. */
  17942. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17943. if (deleteFrames === void 0) { deleteFrames = true; }
  17944. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17945. if (this.animations[i]) {
  17946. this.animations[i].deleteRange(name, deleteFrames);
  17947. }
  17948. }
  17949. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17950. };
  17951. /**
  17952. * Get an animation range by name
  17953. * @param name defines the name of the animation range to look for
  17954. * @returns null if not found else the requested animation range
  17955. */
  17956. Node.prototype.getAnimationRange = function (name) {
  17957. return this._ranges[name];
  17958. };
  17959. /**
  17960. * Will start the animation sequence
  17961. * @param name defines the range frames for animation sequence
  17962. * @param loop defines if the animation should loop (false by default)
  17963. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17964. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17965. * @returns the object created for this animation. If range does not exist, it will return null
  17966. */
  17967. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17968. var range = this.getAnimationRange(name);
  17969. if (!range) {
  17970. return null;
  17971. }
  17972. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17973. };
  17974. /**
  17975. * Serialize animation ranges into a JSON compatible object
  17976. * @returns serialization object
  17977. */
  17978. Node.prototype.serializeAnimationRanges = function () {
  17979. var serializationRanges = [];
  17980. for (var name in this._ranges) {
  17981. var localRange = this._ranges[name];
  17982. if (!localRange) {
  17983. continue;
  17984. }
  17985. var range = {};
  17986. range.name = name;
  17987. range.from = localRange.from;
  17988. range.to = localRange.to;
  17989. serializationRanges.push(range);
  17990. }
  17991. return serializationRanges;
  17992. };
  17993. /**
  17994. * Computes the world matrix of the node
  17995. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17996. * @returns the world matrix
  17997. */
  17998. Node.prototype.computeWorldMatrix = function (force) {
  17999. return BABYLON.Matrix.Identity();
  18000. };
  18001. /**
  18002. * Releases resources associated with this node.
  18003. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18004. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18005. */
  18006. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18007. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18008. if (!doNotRecurse) {
  18009. var nodes = this.getDescendants(true);
  18010. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18011. var node = nodes_1[_i];
  18012. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18013. }
  18014. }
  18015. else {
  18016. var transformNodes = this.getChildTransformNodes(true);
  18017. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18018. var transformNode = transformNodes_1[_a];
  18019. transformNode.parent = null;
  18020. transformNode.computeWorldMatrix(true);
  18021. }
  18022. }
  18023. this.parent = null;
  18024. // Callback
  18025. this.onDisposeObservable.notifyObservers(this);
  18026. this.onDisposeObservable.clear();
  18027. // Behaviors
  18028. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18029. var behavior = _c[_b];
  18030. behavior.detach();
  18031. }
  18032. this._behaviors = [];
  18033. this._isDisposed = true;
  18034. };
  18035. /**
  18036. * Parse animation range data from a serialization object and store them into a given node
  18037. * @param node defines where to store the animation ranges
  18038. * @param parsedNode defines the serialization object to read data from
  18039. * @param scene defines the hosting scene
  18040. */
  18041. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18042. if (parsedNode.ranges) {
  18043. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18044. var data = parsedNode.ranges[index];
  18045. node.createAnimationRange(data.name, data.from, data.to);
  18046. }
  18047. }
  18048. };
  18049. Node._NodeConstructors = {};
  18050. __decorate([
  18051. BABYLON.serialize()
  18052. ], Node.prototype, "name", void 0);
  18053. __decorate([
  18054. BABYLON.serialize()
  18055. ], Node.prototype, "id", void 0);
  18056. __decorate([
  18057. BABYLON.serialize()
  18058. ], Node.prototype, "uniqueId", void 0);
  18059. __decorate([
  18060. BABYLON.serialize()
  18061. ], Node.prototype, "state", void 0);
  18062. __decorate([
  18063. BABYLON.serialize()
  18064. ], Node.prototype, "metadata", void 0);
  18065. return Node;
  18066. }());
  18067. BABYLON.Node = Node;
  18068. })(BABYLON || (BABYLON = {}));
  18069. //# sourceMappingURL=babylon.node.js.map
  18070. var BABYLON;
  18071. (function (BABYLON) {
  18072. // This matrix is used as a value to reset the bounding box.
  18073. var _identityMatrix = BABYLON.Matrix.Identity();
  18074. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18075. var BoundingSphere = /** @class */ (function () {
  18076. /**
  18077. * Creates a new bounding sphere
  18078. * @param min defines the minimum vector (in local space)
  18079. * @param max defines the maximum vector (in local space)
  18080. */
  18081. function BoundingSphere(min, max) {
  18082. this.center = BABYLON.Vector3.Zero();
  18083. this.centerWorld = BABYLON.Vector3.Zero();
  18084. this.reConstruct(min, max);
  18085. }
  18086. /**
  18087. * Recreates the entire bounding sphere from scratch
  18088. * @param min defines the new minimum vector (in local space)
  18089. * @param max defines the new maximum vector (in local space)
  18090. */
  18091. BoundingSphere.prototype.reConstruct = function (min, max) {
  18092. this.minimum = min.clone();
  18093. this.maximum = max.clone();
  18094. var distance = BABYLON.Vector3.Distance(min, max);
  18095. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18096. this.radius = distance * 0.5;
  18097. this.centerWorld.set(0, 0, 0);
  18098. this._update(_identityMatrix);
  18099. };
  18100. /**
  18101. * Scale the current bounding sphere by applying a scale factor
  18102. * @param factor defines the scale factor to apply
  18103. * @returns the current bounding box
  18104. */
  18105. BoundingSphere.prototype.scale = function (factor) {
  18106. var newRadius = this.radius * factor;
  18107. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18108. var min = this.center.subtract(_tempRadiusVector);
  18109. var max = this.center.add(_tempRadiusVector);
  18110. this.reConstruct(min, max);
  18111. return this;
  18112. };
  18113. // Methods
  18114. /** @hidden */
  18115. BoundingSphere.prototype._update = function (world) {
  18116. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18117. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18118. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18119. };
  18120. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18121. for (var i = 0; i < 6; i++) {
  18122. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18123. return false;
  18124. }
  18125. return true;
  18126. };
  18127. BoundingSphere.prototype.intersectsPoint = function (point) {
  18128. var x = this.centerWorld.x - point.x;
  18129. var y = this.centerWorld.y - point.y;
  18130. var z = this.centerWorld.z - point.z;
  18131. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18132. if (this.radiusWorld < distance)
  18133. return false;
  18134. return true;
  18135. };
  18136. // Statics
  18137. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18138. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18139. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18140. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18141. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18142. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18143. return false;
  18144. return true;
  18145. };
  18146. return BoundingSphere;
  18147. }());
  18148. BABYLON.BoundingSphere = BoundingSphere;
  18149. })(BABYLON || (BABYLON = {}));
  18150. //# sourceMappingURL=babylon.boundingSphere.js.map
  18151. var BABYLON;
  18152. (function (BABYLON) {
  18153. var BoundingBox = /** @class */ (function () {
  18154. /**
  18155. * Creates a new bounding box
  18156. * @param min defines the minimum vector (in local space)
  18157. * @param max defines the maximum vector (in local space)
  18158. */
  18159. function BoundingBox(min, max) {
  18160. this.vectorsWorld = new Array();
  18161. this.reConstruct(min, max);
  18162. }
  18163. // Methods
  18164. /**
  18165. * Recreates the entire bounding box from scratch
  18166. * @param min defines the new minimum vector (in local space)
  18167. * @param max defines the new maximum vector (in local space)
  18168. */
  18169. BoundingBox.prototype.reConstruct = function (min, max) {
  18170. this.minimum = min.clone();
  18171. this.maximum = max.clone();
  18172. // Bounding vectors
  18173. this.vectors = [
  18174. this.minimum.clone(),
  18175. this.maximum.clone(),
  18176. this.minimum.clone(),
  18177. this.minimum.clone(),
  18178. this.minimum.clone(),
  18179. this.maximum.clone(),
  18180. this.maximum.clone(),
  18181. this.maximum.clone()
  18182. ];
  18183. this.vectors[2].x = this.maximum.x;
  18184. this.vectors[3].y = this.maximum.y;
  18185. this.vectors[4].z = this.maximum.z;
  18186. this.vectors[5].z = this.minimum.z;
  18187. this.vectors[6].x = this.minimum.x;
  18188. this.vectors[7].y = this.minimum.y;
  18189. // OBB
  18190. this.center = this.maximum.add(this.minimum).scale(0.5);
  18191. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18192. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18193. // World
  18194. for (var index = 0; index < this.vectors.length; index++) {
  18195. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18196. }
  18197. this.minimumWorld = BABYLON.Vector3.Zero();
  18198. this.maximumWorld = BABYLON.Vector3.Zero();
  18199. this.centerWorld = BABYLON.Vector3.Zero();
  18200. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18201. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18202. };
  18203. /**
  18204. * Scale the current bounding box by applying a scale factor
  18205. * @param factor defines the scale factor to apply
  18206. * @returns the current bounding box
  18207. */
  18208. BoundingBox.prototype.scale = function (factor) {
  18209. var diff = this.maximum.subtract(this.minimum);
  18210. var distance = diff.length() * factor;
  18211. diff.normalize();
  18212. var newRadius = diff.scale(distance / 2);
  18213. var min = this.center.subtract(newRadius);
  18214. var max = this.center.add(newRadius);
  18215. this.reConstruct(min, max);
  18216. return this;
  18217. };
  18218. BoundingBox.prototype.getWorldMatrix = function () {
  18219. return this._worldMatrix;
  18220. };
  18221. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18222. this._worldMatrix.copyFrom(matrix);
  18223. return this;
  18224. };
  18225. /** @hidden */
  18226. BoundingBox.prototype._update = function (world) {
  18227. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18228. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18229. for (var index = 0; index < this.vectors.length; index++) {
  18230. var v = this.vectorsWorld[index];
  18231. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18232. if (v.x < this.minimumWorld.x)
  18233. this.minimumWorld.x = v.x;
  18234. if (v.y < this.minimumWorld.y)
  18235. this.minimumWorld.y = v.y;
  18236. if (v.z < this.minimumWorld.z)
  18237. this.minimumWorld.z = v.z;
  18238. if (v.x > this.maximumWorld.x)
  18239. this.maximumWorld.x = v.x;
  18240. if (v.y > this.maximumWorld.y)
  18241. this.maximumWorld.y = v.y;
  18242. if (v.z > this.maximumWorld.z)
  18243. this.maximumWorld.z = v.z;
  18244. }
  18245. // Extend
  18246. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18247. this.extendSizeWorld.scaleInPlace(0.5);
  18248. // OBB
  18249. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18250. this.centerWorld.scaleInPlace(0.5);
  18251. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18252. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18253. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18254. this._worldMatrix = world;
  18255. };
  18256. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18257. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18258. };
  18259. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18260. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18261. };
  18262. BoundingBox.prototype.intersectsPoint = function (point) {
  18263. var delta = -BABYLON.Epsilon;
  18264. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18265. return false;
  18266. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18267. return false;
  18268. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18269. return false;
  18270. return true;
  18271. };
  18272. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18273. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18274. };
  18275. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18276. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18277. return false;
  18278. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18279. return false;
  18280. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18281. return false;
  18282. return true;
  18283. };
  18284. // Statics
  18285. BoundingBox.Intersects = function (box0, box1) {
  18286. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18287. return false;
  18288. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18289. return false;
  18290. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18291. return false;
  18292. return true;
  18293. };
  18294. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18295. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18296. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18297. return (num <= (sphereRadius * sphereRadius));
  18298. };
  18299. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18300. for (var p = 0; p < 6; p++) {
  18301. for (var i = 0; i < 8; i++) {
  18302. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18303. return false;
  18304. }
  18305. }
  18306. }
  18307. return true;
  18308. };
  18309. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18310. for (var p = 0; p < 6; p++) {
  18311. var inCount = 8;
  18312. for (var i = 0; i < 8; i++) {
  18313. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18314. --inCount;
  18315. }
  18316. else {
  18317. break;
  18318. }
  18319. }
  18320. if (inCount === 0)
  18321. return false;
  18322. }
  18323. return true;
  18324. };
  18325. return BoundingBox;
  18326. }());
  18327. BABYLON.BoundingBox = BoundingBox;
  18328. })(BABYLON || (BABYLON = {}));
  18329. //# sourceMappingURL=babylon.boundingBox.js.map
  18330. var BABYLON;
  18331. (function (BABYLON) {
  18332. var computeBoxExtents = function (axis, box) {
  18333. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18334. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18335. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18336. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18337. var r = r0 + r1 + r2;
  18338. return {
  18339. min: p - r,
  18340. max: p + r
  18341. };
  18342. };
  18343. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18344. var axisOverlap = function (axis, box0, box1) {
  18345. var result0 = computeBoxExtents(axis, box0);
  18346. var result1 = computeBoxExtents(axis, box1);
  18347. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18348. };
  18349. var BoundingInfo = /** @class */ (function () {
  18350. function BoundingInfo(minimum, maximum) {
  18351. this.minimum = minimum;
  18352. this.maximum = maximum;
  18353. this._isLocked = false;
  18354. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18355. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18356. }
  18357. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18358. get: function () {
  18359. return this._isLocked;
  18360. },
  18361. set: function (value) {
  18362. this._isLocked = value;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. // Methods
  18368. BoundingInfo.prototype.update = function (world) {
  18369. if (this._isLocked) {
  18370. return;
  18371. }
  18372. this.boundingBox._update(world);
  18373. this.boundingSphere._update(world);
  18374. };
  18375. /**
  18376. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18377. * @param center New center of the bounding info
  18378. * @param extend New extend of the bounding info
  18379. */
  18380. BoundingInfo.prototype.centerOn = function (center, extend) {
  18381. this.minimum = center.subtract(extend);
  18382. this.maximum = center.add(extend);
  18383. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18384. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18385. return this;
  18386. };
  18387. /**
  18388. * Scale the current bounding info by applying a scale factor
  18389. * @param factor defines the scale factor to apply
  18390. * @returns the current bounding info
  18391. */
  18392. BoundingInfo.prototype.scale = function (factor) {
  18393. this.boundingBox.scale(factor);
  18394. this.boundingSphere.scale(factor);
  18395. return this;
  18396. };
  18397. /**
  18398. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18399. * @param frustumPlanes defines the frustum to test
  18400. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18401. * @returns true if the bounding info is in the frustum planes
  18402. */
  18403. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18404. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18405. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18406. return false;
  18407. }
  18408. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18409. return true;
  18410. }
  18411. return this.boundingBox.isInFrustum(frustumPlanes);
  18412. };
  18413. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18414. /**
  18415. * Gets the world distance between the min and max points of the bounding box
  18416. */
  18417. get: function () {
  18418. var boundingBox = this.boundingBox;
  18419. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18420. return size.length();
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18426. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18427. };
  18428. /** @hidden */
  18429. BoundingInfo.prototype._checkCollision = function (collider) {
  18430. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18431. };
  18432. BoundingInfo.prototype.intersectsPoint = function (point) {
  18433. if (!this.boundingSphere.centerWorld) {
  18434. return false;
  18435. }
  18436. if (!this.boundingSphere.intersectsPoint(point)) {
  18437. return false;
  18438. }
  18439. if (!this.boundingBox.intersectsPoint(point)) {
  18440. return false;
  18441. }
  18442. return true;
  18443. };
  18444. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18445. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18446. return false;
  18447. }
  18448. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18449. return false;
  18450. }
  18451. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18452. return false;
  18453. }
  18454. if (!precise) {
  18455. return true;
  18456. }
  18457. var box0 = this.boundingBox;
  18458. var box1 = boundingInfo.boundingBox;
  18459. if (!axisOverlap(box0.directions[0], box0, box1))
  18460. return false;
  18461. if (!axisOverlap(box0.directions[1], box0, box1))
  18462. return false;
  18463. if (!axisOverlap(box0.directions[2], box0, box1))
  18464. return false;
  18465. if (!axisOverlap(box1.directions[0], box0, box1))
  18466. return false;
  18467. if (!axisOverlap(box1.directions[1], box0, box1))
  18468. return false;
  18469. if (!axisOverlap(box1.directions[2], box0, box1))
  18470. return false;
  18471. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18472. return false;
  18473. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18474. return false;
  18475. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18476. return false;
  18477. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18478. return false;
  18479. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18480. return false;
  18481. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18482. return false;
  18483. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18484. return false;
  18485. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18486. return false;
  18487. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18488. return false;
  18489. return true;
  18490. };
  18491. return BoundingInfo;
  18492. }());
  18493. BABYLON.BoundingInfo = BoundingInfo;
  18494. })(BABYLON || (BABYLON = {}));
  18495. //# sourceMappingURL=babylon.boundingInfo.js.map
  18496. var BABYLON;
  18497. (function (BABYLON) {
  18498. var TransformNode = /** @class */ (function (_super) {
  18499. __extends(TransformNode, _super);
  18500. function TransformNode(name, scene, isPure) {
  18501. if (scene === void 0) { scene = null; }
  18502. if (isPure === void 0) { isPure = true; }
  18503. var _this = _super.call(this, name, scene) || this;
  18504. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18505. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18506. _this._up = new BABYLON.Vector3(0, 1, 0);
  18507. _this._right = new BABYLON.Vector3(1, 0, 0);
  18508. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18509. // Properties
  18510. _this._rotation = BABYLON.Vector3.Zero();
  18511. _this._scaling = BABYLON.Vector3.One();
  18512. _this._isDirty = false;
  18513. /**
  18514. * Set the billboard mode. Default is 0.
  18515. *
  18516. * | Value | Type | Description |
  18517. * | --- | --- | --- |
  18518. * | 0 | BILLBOARDMODE_NONE | |
  18519. * | 1 | BILLBOARDMODE_X | |
  18520. * | 2 | BILLBOARDMODE_Y | |
  18521. * | 4 | BILLBOARDMODE_Z | |
  18522. * | 7 | BILLBOARDMODE_ALL | |
  18523. *
  18524. */
  18525. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18526. _this.scalingDeterminant = 1;
  18527. _this.infiniteDistance = false;
  18528. /**
  18529. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18530. * By default the system will update normals to compensate
  18531. */
  18532. _this.ignoreNonUniformScaling = false;
  18533. _this.position = BABYLON.Vector3.Zero();
  18534. _this._localWorld = BABYLON.Matrix.Zero();
  18535. /** @hidden */
  18536. _this._worldMatrix = BABYLON.Matrix.Zero();
  18537. /** @hidden */
  18538. _this._worldMatrixDeterminant = 0;
  18539. _this._absolutePosition = BABYLON.Vector3.Zero();
  18540. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18541. _this._postMultiplyPivotMatrix = false;
  18542. _this._isWorldMatrixFrozen = false;
  18543. /**
  18544. * An event triggered after the world matrix is updated
  18545. */
  18546. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18547. _this._nonUniformScaling = false;
  18548. if (isPure) {
  18549. _this.getScene().addTransformNode(_this);
  18550. }
  18551. return _this;
  18552. }
  18553. /**
  18554. * Gets a string identifying the name of the class
  18555. * @returns "TransformNode" string
  18556. */
  18557. TransformNode.prototype.getClassName = function () {
  18558. return "TransformNode";
  18559. };
  18560. Object.defineProperty(TransformNode.prototype, "rotation", {
  18561. /**
  18562. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18563. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18564. * Default : (0.0, 0.0, 0.0)
  18565. */
  18566. get: function () {
  18567. return this._rotation;
  18568. },
  18569. set: function (newRotation) {
  18570. this._rotation = newRotation;
  18571. },
  18572. enumerable: true,
  18573. configurable: true
  18574. });
  18575. Object.defineProperty(TransformNode.prototype, "scaling", {
  18576. /**
  18577. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18578. * Default : (1.0, 1.0, 1.0)
  18579. */
  18580. get: function () {
  18581. return this._scaling;
  18582. },
  18583. /**
  18584. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18585. * Default : (1.0, 1.0, 1.0)
  18586. */
  18587. set: function (newScaling) {
  18588. this._scaling = newScaling;
  18589. },
  18590. enumerable: true,
  18591. configurable: true
  18592. });
  18593. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18594. /**
  18595. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18596. * It's null by default.
  18597. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18598. */
  18599. get: function () {
  18600. return this._rotationQuaternion;
  18601. },
  18602. set: function (quaternion) {
  18603. this._rotationQuaternion = quaternion;
  18604. //reset the rotation vector.
  18605. if (quaternion && this.rotation.length()) {
  18606. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18607. }
  18608. },
  18609. enumerable: true,
  18610. configurable: true
  18611. });
  18612. Object.defineProperty(TransformNode.prototype, "forward", {
  18613. /**
  18614. * The forward direction of that transform in world space.
  18615. */
  18616. get: function () {
  18617. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18618. },
  18619. enumerable: true,
  18620. configurable: true
  18621. });
  18622. Object.defineProperty(TransformNode.prototype, "up", {
  18623. /**
  18624. * The up direction of that transform in world space.
  18625. */
  18626. get: function () {
  18627. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18628. },
  18629. enumerable: true,
  18630. configurable: true
  18631. });
  18632. Object.defineProperty(TransformNode.prototype, "right", {
  18633. /**
  18634. * The right direction of that transform in world space.
  18635. */
  18636. get: function () {
  18637. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18638. },
  18639. enumerable: true,
  18640. configurable: true
  18641. });
  18642. /**
  18643. * Returns the latest update of the World matrix
  18644. * Returns a Matrix.
  18645. */
  18646. TransformNode.prototype.getWorldMatrix = function () {
  18647. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18648. this.computeWorldMatrix();
  18649. }
  18650. return this._worldMatrix;
  18651. };
  18652. /** @hidden */
  18653. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18654. return this._worldMatrixDeterminant;
  18655. };
  18656. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18657. /**
  18658. * Returns directly the latest state of the mesh World matrix.
  18659. * A Matrix is returned.
  18660. */
  18661. get: function () {
  18662. return this._worldMatrix;
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. /**
  18668. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18669. * Returns the TransformNode.
  18670. */
  18671. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18672. this._poseMatrix.copyFrom(matrix);
  18673. return this;
  18674. };
  18675. /**
  18676. * Returns the mesh Pose matrix.
  18677. * Returned object : Matrix
  18678. */
  18679. TransformNode.prototype.getPoseMatrix = function () {
  18680. return this._poseMatrix;
  18681. };
  18682. /** @hidden */
  18683. TransformNode.prototype._isSynchronized = function () {
  18684. if (this._isDirty) {
  18685. return false;
  18686. }
  18687. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18688. return false;
  18689. if (this._cache.pivotMatrixUpdated) {
  18690. return false;
  18691. }
  18692. if (this.infiniteDistance) {
  18693. return false;
  18694. }
  18695. if (!this._cache.position.equals(this.position))
  18696. return false;
  18697. if (this._rotationQuaternion) {
  18698. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18699. return false;
  18700. }
  18701. if (!this._cache.rotation.equals(this.rotation))
  18702. return false;
  18703. if (!this._cache.scaling.equals(this.scaling))
  18704. return false;
  18705. return true;
  18706. };
  18707. /** @hidden */
  18708. TransformNode.prototype._initCache = function () {
  18709. _super.prototype._initCache.call(this);
  18710. this._cache.localMatrixUpdated = false;
  18711. this._cache.position = BABYLON.Vector3.Zero();
  18712. this._cache.scaling = BABYLON.Vector3.Zero();
  18713. this._cache.rotation = BABYLON.Vector3.Zero();
  18714. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18715. this._cache.billboardMode = -1;
  18716. };
  18717. TransformNode.prototype.markAsDirty = function (property) {
  18718. if (property === "rotation") {
  18719. this.rotationQuaternion = null;
  18720. }
  18721. this._currentRenderId = Number.MAX_VALUE;
  18722. this._isDirty = true;
  18723. return this;
  18724. };
  18725. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18726. /**
  18727. * Returns the current mesh absolute position.
  18728. * Returns a Vector3.
  18729. */
  18730. get: function () {
  18731. return this._absolutePosition;
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. /**
  18737. * Sets a new matrix to apply before all other transformation
  18738. * @param matrix defines the transform matrix
  18739. * @returns the current TransformNode
  18740. */
  18741. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18742. return this.setPivotMatrix(matrix, false);
  18743. };
  18744. /**
  18745. * Sets a new pivot matrix to the current node
  18746. * @param matrix defines the new pivot matrix to use
  18747. * @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
  18748. * @returns the current TransformNode
  18749. */
  18750. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18751. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18752. this._pivotMatrix = matrix.clone();
  18753. this._cache.pivotMatrixUpdated = true;
  18754. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18755. if (this._postMultiplyPivotMatrix) {
  18756. if (!this._pivotMatrixInverse) {
  18757. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18758. }
  18759. else {
  18760. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18761. }
  18762. }
  18763. return this;
  18764. };
  18765. /**
  18766. * Returns the mesh pivot matrix.
  18767. * Default : Identity.
  18768. * A Matrix is returned.
  18769. */
  18770. TransformNode.prototype.getPivotMatrix = function () {
  18771. return this._pivotMatrix;
  18772. };
  18773. /**
  18774. * Prevents the World matrix to be computed any longer.
  18775. * Returns the TransformNode.
  18776. */
  18777. TransformNode.prototype.freezeWorldMatrix = function () {
  18778. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18779. this.computeWorldMatrix(true);
  18780. this._isWorldMatrixFrozen = true;
  18781. return this;
  18782. };
  18783. /**
  18784. * Allows back the World matrix computation.
  18785. * Returns the TransformNode.
  18786. */
  18787. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18788. this._isWorldMatrixFrozen = false;
  18789. this.computeWorldMatrix(true);
  18790. return this;
  18791. };
  18792. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18793. /**
  18794. * True if the World matrix has been frozen.
  18795. * Returns a boolean.
  18796. */
  18797. get: function () {
  18798. return this._isWorldMatrixFrozen;
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. /**
  18804. * Retuns the mesh absolute position in the World.
  18805. * Returns a Vector3.
  18806. */
  18807. TransformNode.prototype.getAbsolutePosition = function () {
  18808. this.computeWorldMatrix();
  18809. return this._absolutePosition;
  18810. };
  18811. /**
  18812. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18813. * Returns the TransformNode.
  18814. */
  18815. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18816. if (!absolutePosition) {
  18817. return this;
  18818. }
  18819. var absolutePositionX;
  18820. var absolutePositionY;
  18821. var absolutePositionZ;
  18822. if (absolutePosition.x === undefined) {
  18823. if (arguments.length < 3) {
  18824. return this;
  18825. }
  18826. absolutePositionX = arguments[0];
  18827. absolutePositionY = arguments[1];
  18828. absolutePositionZ = arguments[2];
  18829. }
  18830. else {
  18831. absolutePositionX = absolutePosition.x;
  18832. absolutePositionY = absolutePosition.y;
  18833. absolutePositionZ = absolutePosition.z;
  18834. }
  18835. if (this.parent) {
  18836. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18837. invertParentWorldMatrix.invert();
  18838. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18839. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18840. }
  18841. else {
  18842. this.position.x = absolutePositionX;
  18843. this.position.y = absolutePositionY;
  18844. this.position.z = absolutePositionZ;
  18845. }
  18846. return this;
  18847. };
  18848. /**
  18849. * Sets the mesh position in its local space.
  18850. * Returns the TransformNode.
  18851. */
  18852. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18853. this.computeWorldMatrix();
  18854. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18855. return this;
  18856. };
  18857. /**
  18858. * Returns the mesh position in the local space from the current World matrix values.
  18859. * Returns a new Vector3.
  18860. */
  18861. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18862. this.computeWorldMatrix();
  18863. var invLocalWorldMatrix = this._localWorld.clone();
  18864. invLocalWorldMatrix.invert();
  18865. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18866. };
  18867. /**
  18868. * Translates the mesh along the passed Vector3 in its local space.
  18869. * Returns the TransformNode.
  18870. */
  18871. TransformNode.prototype.locallyTranslate = function (vector3) {
  18872. this.computeWorldMatrix(true);
  18873. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18874. return this;
  18875. };
  18876. /**
  18877. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18878. * @param targetPoint the position (must be in same space as current mesh) to look at
  18879. * @param yawCor optional yaw (y-axis) correction in radians
  18880. * @param pitchCor optional pitch (x-axis) correction in radians
  18881. * @param rollCor optional roll (z-axis) correction in radians
  18882. * @param space the choosen space of the target
  18883. * @returns the TransformNode.
  18884. */
  18885. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18886. if (yawCor === void 0) { yawCor = 0; }
  18887. if (pitchCor === void 0) { pitchCor = 0; }
  18888. if (rollCor === void 0) { rollCor = 0; }
  18889. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18890. var dv = TransformNode._lookAtVectorCache;
  18891. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18892. targetPoint.subtractToRef(pos, dv);
  18893. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18894. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18895. var pitch = Math.atan2(dv.y, len);
  18896. if (this.rotationQuaternion) {
  18897. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18898. }
  18899. else {
  18900. this.rotation.x = pitch + pitchCor;
  18901. this.rotation.y = yaw + yawCor;
  18902. this.rotation.z = rollCor;
  18903. }
  18904. return this;
  18905. };
  18906. /**
  18907. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18908. * This Vector3 is expressed in the World space.
  18909. */
  18910. TransformNode.prototype.getDirection = function (localAxis) {
  18911. var result = BABYLON.Vector3.Zero();
  18912. this.getDirectionToRef(localAxis, result);
  18913. return result;
  18914. };
  18915. /**
  18916. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18917. * localAxis is expressed in the mesh local space.
  18918. * result is computed in the Wordl space from the mesh World matrix.
  18919. * Returns the TransformNode.
  18920. */
  18921. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18922. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18923. return this;
  18924. };
  18925. /**
  18926. * Sets a new pivot point to the current node
  18927. * @param point defines the new pivot point to use
  18928. * @param space defines if the point is in world or local space (local by default)
  18929. * @returns the current TransformNode
  18930. */
  18931. TransformNode.prototype.setPivotPoint = function (point, space) {
  18932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18933. if (this.getScene().getRenderId() == 0) {
  18934. this.computeWorldMatrix(true);
  18935. }
  18936. var wm = this.getWorldMatrix();
  18937. if (space == BABYLON.Space.WORLD) {
  18938. var tmat = BABYLON.Tmp.Matrix[0];
  18939. wm.invertToRef(tmat);
  18940. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18941. }
  18942. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18943. };
  18944. /**
  18945. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18946. */
  18947. TransformNode.prototype.getPivotPoint = function () {
  18948. var point = BABYLON.Vector3.Zero();
  18949. this.getPivotPointToRef(point);
  18950. return point;
  18951. };
  18952. /**
  18953. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18954. * Returns the TransformNode.
  18955. */
  18956. TransformNode.prototype.getPivotPointToRef = function (result) {
  18957. result.x = -this._pivotMatrix.m[12];
  18958. result.y = -this._pivotMatrix.m[13];
  18959. result.z = -this._pivotMatrix.m[14];
  18960. return this;
  18961. };
  18962. /**
  18963. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18964. */
  18965. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18966. var point = BABYLON.Vector3.Zero();
  18967. this.getAbsolutePivotPointToRef(point);
  18968. return point;
  18969. };
  18970. /**
  18971. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18972. * Returns the TransformNode.
  18973. */
  18974. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18975. result.x = this._pivotMatrix.m[12];
  18976. result.y = this._pivotMatrix.m[13];
  18977. result.z = this._pivotMatrix.m[14];
  18978. this.getPivotPointToRef(result);
  18979. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18980. return this;
  18981. };
  18982. /**
  18983. * Defines the passed node as the parent of the current node.
  18984. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18985. * Returns the TransformNode.
  18986. */
  18987. TransformNode.prototype.setParent = function (node) {
  18988. if (!node && !this.parent) {
  18989. return this;
  18990. }
  18991. if (!node) {
  18992. var rotation = BABYLON.Tmp.Quaternion[0];
  18993. var position = BABYLON.Tmp.Vector3[0];
  18994. var scale = BABYLON.Tmp.Vector3[1];
  18995. if (this.parent && this.parent.computeWorldMatrix) {
  18996. this.parent.computeWorldMatrix(true);
  18997. }
  18998. this.computeWorldMatrix(true);
  18999. this.getWorldMatrix().decompose(scale, rotation, position);
  19000. if (this.rotationQuaternion) {
  19001. this.rotationQuaternion.copyFrom(rotation);
  19002. }
  19003. else {
  19004. rotation.toEulerAnglesToRef(this.rotation);
  19005. }
  19006. this.scaling.x = scale.x;
  19007. this.scaling.y = scale.y;
  19008. this.scaling.z = scale.z;
  19009. this.position.x = position.x;
  19010. this.position.y = position.y;
  19011. this.position.z = position.z;
  19012. }
  19013. else {
  19014. var rotation = BABYLON.Tmp.Quaternion[0];
  19015. var position = BABYLON.Tmp.Vector3[0];
  19016. var scale = BABYLON.Tmp.Vector3[1];
  19017. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19018. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19019. this.computeWorldMatrix(true);
  19020. node.computeWorldMatrix(true);
  19021. node.getWorldMatrix().invertToRef(invParentMatrix);
  19022. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19023. diffMatrix.decompose(scale, rotation, position);
  19024. if (this.rotationQuaternion) {
  19025. this.rotationQuaternion.copyFrom(rotation);
  19026. }
  19027. else {
  19028. rotation.toEulerAnglesToRef(this.rotation);
  19029. }
  19030. this.position.x = position.x;
  19031. this.position.y = position.y;
  19032. this.position.z = position.z;
  19033. this.scaling.x = scale.x;
  19034. this.scaling.y = scale.y;
  19035. this.scaling.z = scale.z;
  19036. }
  19037. this.parent = node;
  19038. return this;
  19039. };
  19040. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19041. get: function () {
  19042. return this._nonUniformScaling;
  19043. },
  19044. enumerable: true,
  19045. configurable: true
  19046. });
  19047. /** @hidden */
  19048. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19049. if (this._nonUniformScaling === value) {
  19050. return false;
  19051. }
  19052. this._nonUniformScaling = value;
  19053. return true;
  19054. };
  19055. /**
  19056. * Attach the current TransformNode to another TransformNode associated with a bone
  19057. * @param bone Bone affecting the TransformNode
  19058. * @param affectedTransformNode TransformNode associated with the bone
  19059. */
  19060. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19061. this._transformToBoneReferal = affectedTransformNode;
  19062. this.parent = bone;
  19063. if (bone.getWorldMatrix().determinant() < 0) {
  19064. this.scalingDeterminant *= -1;
  19065. }
  19066. return this;
  19067. };
  19068. TransformNode.prototype.detachFromBone = function () {
  19069. if (!this.parent) {
  19070. return this;
  19071. }
  19072. if (this.parent.getWorldMatrix().determinant() < 0) {
  19073. this.scalingDeterminant *= -1;
  19074. }
  19075. this._transformToBoneReferal = null;
  19076. this.parent = null;
  19077. return this;
  19078. };
  19079. /**
  19080. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19081. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19082. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19083. * The passed axis is also normalized.
  19084. * Returns the TransformNode.
  19085. */
  19086. TransformNode.prototype.rotate = function (axis, amount, space) {
  19087. axis.normalize();
  19088. if (!this.rotationQuaternion) {
  19089. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19090. this.rotation = BABYLON.Vector3.Zero();
  19091. }
  19092. var rotationQuaternion;
  19093. if (!space || space === BABYLON.Space.LOCAL) {
  19094. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19095. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19096. }
  19097. else {
  19098. if (this.parent) {
  19099. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19100. invertParentWorldMatrix.invert();
  19101. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19102. }
  19103. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19104. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19105. }
  19106. return this;
  19107. };
  19108. /**
  19109. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19110. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19111. * The passed axis is also normalized.
  19112. * Returns the TransformNode.
  19113. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19114. */
  19115. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19116. axis.normalize();
  19117. if (!this.rotationQuaternion) {
  19118. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19119. this.rotation.copyFromFloats(0, 0, 0);
  19120. }
  19121. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19122. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19123. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19124. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19125. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19126. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19127. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19128. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19129. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19130. return this;
  19131. };
  19132. /**
  19133. * Translates the mesh along the axis vector for the passed distance in the given space.
  19134. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19135. * Returns the TransformNode.
  19136. */
  19137. TransformNode.prototype.translate = function (axis, distance, space) {
  19138. var displacementVector = axis.scale(distance);
  19139. if (!space || space === BABYLON.Space.LOCAL) {
  19140. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19141. this.setPositionWithLocalVector(tempV3);
  19142. }
  19143. else {
  19144. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19145. }
  19146. return this;
  19147. };
  19148. /**
  19149. * Adds a rotation step to the mesh current rotation.
  19150. * x, y, z are Euler angles expressed in radians.
  19151. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19152. * This means this rotation is made in the mesh local space only.
  19153. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19154. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19155. * ```javascript
  19156. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19157. * ```
  19158. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19159. * 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.
  19160. * Returns the TransformNode.
  19161. */
  19162. TransformNode.prototype.addRotation = function (x, y, z) {
  19163. var rotationQuaternion;
  19164. if (this.rotationQuaternion) {
  19165. rotationQuaternion = this.rotationQuaternion;
  19166. }
  19167. else {
  19168. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19169. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19170. }
  19171. var accumulation = BABYLON.Tmp.Quaternion[0];
  19172. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19173. rotationQuaternion.multiplyInPlace(accumulation);
  19174. if (!this.rotationQuaternion) {
  19175. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19176. }
  19177. return this;
  19178. };
  19179. /**
  19180. * Computes the mesh World matrix and returns it.
  19181. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19182. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19183. * If the parameter `force`is set to `true`, the actual computation is done.
  19184. * Returns the mesh World Matrix.
  19185. */
  19186. TransformNode.prototype.computeWorldMatrix = function (force) {
  19187. if (this._isWorldMatrixFrozen) {
  19188. return this._worldMatrix;
  19189. }
  19190. if (!force && this.isSynchronized(true)) {
  19191. this._currentRenderId = this.getScene().getRenderId();
  19192. return this._worldMatrix;
  19193. }
  19194. this._cache.position.copyFrom(this.position);
  19195. this._cache.scaling.copyFrom(this.scaling);
  19196. this._cache.pivotMatrixUpdated = false;
  19197. this._cache.billboardMode = this.billboardMode;
  19198. this._currentRenderId = this.getScene().getRenderId();
  19199. this._childRenderId = this.getScene().getRenderId();
  19200. this._isDirty = false;
  19201. // Scaling
  19202. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19203. // Rotation
  19204. //rotate, if quaternion is set and rotation was used
  19205. if (this.rotationQuaternion) {
  19206. var len = this.rotation.length();
  19207. if (len) {
  19208. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19209. this.rotation.copyFromFloats(0, 0, 0);
  19210. }
  19211. }
  19212. if (this.rotationQuaternion) {
  19213. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19214. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19215. }
  19216. else {
  19217. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19218. this._cache.rotation.copyFrom(this.rotation);
  19219. }
  19220. // Translation
  19221. var camera = this.getScene().activeCamera;
  19222. if (this.infiniteDistance && !this.parent && camera) {
  19223. var cameraWorldMatrix = camera.getWorldMatrix();
  19224. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19225. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19226. }
  19227. else {
  19228. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19229. }
  19230. // Composing transformations
  19231. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19232. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19233. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19234. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19235. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19236. // Need to decompose each rotation here
  19237. var currentPosition = BABYLON.Tmp.Vector3[3];
  19238. if (this.parent && this.parent.getWorldMatrix) {
  19239. if (this._transformToBoneReferal) {
  19240. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19241. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19242. }
  19243. else {
  19244. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19245. }
  19246. }
  19247. else {
  19248. currentPosition.copyFrom(this.position);
  19249. }
  19250. currentPosition.subtractInPlace(camera.globalPosition);
  19251. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19252. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19253. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19254. }
  19255. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19256. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19257. }
  19258. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19259. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19260. }
  19261. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19262. }
  19263. else {
  19264. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19265. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19266. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19267. }
  19268. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19269. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19270. }
  19271. // Post multiply inverse of pivotMatrix
  19272. if (this._postMultiplyPivotMatrix) {
  19273. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19274. }
  19275. // Local world
  19276. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19277. // Parent
  19278. if (this.parent && this.parent.getWorldMatrix) {
  19279. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19280. if (this._transformToBoneReferal) {
  19281. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19282. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19283. }
  19284. else {
  19285. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19286. }
  19287. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19288. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19289. this._worldMatrix.copyFrom(this._localWorld);
  19290. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19291. }
  19292. else {
  19293. if (this._transformToBoneReferal) {
  19294. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19295. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19296. }
  19297. else {
  19298. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19299. }
  19300. }
  19301. this._markSyncedWithParent();
  19302. }
  19303. else {
  19304. this._worldMatrix.copyFrom(this._localWorld);
  19305. }
  19306. // Normal matrix
  19307. if (!this.ignoreNonUniformScaling) {
  19308. if (this.scaling.isNonUniform) {
  19309. this._updateNonUniformScalingState(true);
  19310. }
  19311. else if (this.parent && this.parent._nonUniformScaling) {
  19312. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19313. }
  19314. else {
  19315. this._updateNonUniformScalingState(false);
  19316. }
  19317. }
  19318. else {
  19319. this._updateNonUniformScalingState(false);
  19320. }
  19321. this._afterComputeWorldMatrix();
  19322. // Absolute position
  19323. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19324. // Callbacks
  19325. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19326. if (!this._poseMatrix) {
  19327. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19328. }
  19329. // Cache the determinant
  19330. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19331. return this._worldMatrix;
  19332. };
  19333. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19334. };
  19335. /**
  19336. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19337. * @param func: callback function to add
  19338. *
  19339. * Returns the TransformNode.
  19340. */
  19341. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19342. this.onAfterWorldMatrixUpdateObservable.add(func);
  19343. return this;
  19344. };
  19345. /**
  19346. * Removes a registered callback function.
  19347. * Returns the TransformNode.
  19348. */
  19349. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19350. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19351. return this;
  19352. };
  19353. /**
  19354. * Clone the current transform node
  19355. * Returns the new transform node
  19356. * @param name Name of the new clone
  19357. * @param newParent New parent for the clone
  19358. * @param doNotCloneChildren Do not clone children hierarchy
  19359. */
  19360. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19361. var _this = this;
  19362. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19363. result.name = name;
  19364. result.id = name;
  19365. if (newParent) {
  19366. result.parent = newParent;
  19367. }
  19368. if (!doNotCloneChildren) {
  19369. // Children
  19370. var directDescendants = this.getDescendants(true);
  19371. for (var index = 0; index < directDescendants.length; index++) {
  19372. var child = directDescendants[index];
  19373. if (child.clone) {
  19374. child.clone(name + "." + child.name, result);
  19375. }
  19376. }
  19377. }
  19378. return result;
  19379. };
  19380. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19381. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19382. serializationObject.type = this.getClassName();
  19383. // Parent
  19384. if (this.parent) {
  19385. serializationObject.parentId = this.parent.id;
  19386. }
  19387. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19388. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19389. }
  19390. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19391. serializationObject.isEnabled = this.isEnabled();
  19392. // Parent
  19393. if (this.parent) {
  19394. serializationObject.parentId = this.parent.id;
  19395. }
  19396. return serializationObject;
  19397. };
  19398. // Statics
  19399. /**
  19400. * Returns a new TransformNode object parsed from the source provided.
  19401. * The parameter `parsedMesh` is the source.
  19402. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19403. */
  19404. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19405. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19406. if (BABYLON.Tags) {
  19407. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19408. }
  19409. if (parsedTransformNode.localMatrix) {
  19410. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19411. }
  19412. else if (parsedTransformNode.pivotMatrix) {
  19413. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19414. }
  19415. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19416. // Parent
  19417. if (parsedTransformNode.parentId) {
  19418. transformNode._waitingParentId = parsedTransformNode.parentId;
  19419. }
  19420. return transformNode;
  19421. };
  19422. /**
  19423. * Releases resources associated with this transform node.
  19424. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19425. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19426. */
  19427. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19428. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19429. // Animations
  19430. this.getScene().stopAnimation(this);
  19431. // Remove from scene
  19432. this.getScene().removeTransformNode(this);
  19433. this.onAfterWorldMatrixUpdateObservable.clear();
  19434. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19435. };
  19436. // Statics
  19437. TransformNode.BILLBOARDMODE_NONE = 0;
  19438. TransformNode.BILLBOARDMODE_X = 1;
  19439. TransformNode.BILLBOARDMODE_Y = 2;
  19440. TransformNode.BILLBOARDMODE_Z = 4;
  19441. TransformNode.BILLBOARDMODE_ALL = 7;
  19442. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19443. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19444. __decorate([
  19445. BABYLON.serializeAsVector3()
  19446. ], TransformNode.prototype, "_rotation", void 0);
  19447. __decorate([
  19448. BABYLON.serializeAsQuaternion()
  19449. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19450. __decorate([
  19451. BABYLON.serializeAsVector3()
  19452. ], TransformNode.prototype, "_scaling", void 0);
  19453. __decorate([
  19454. BABYLON.serialize()
  19455. ], TransformNode.prototype, "billboardMode", void 0);
  19456. __decorate([
  19457. BABYLON.serialize()
  19458. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19459. __decorate([
  19460. BABYLON.serialize()
  19461. ], TransformNode.prototype, "infiniteDistance", void 0);
  19462. __decorate([
  19463. BABYLON.serialize()
  19464. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19465. __decorate([
  19466. BABYLON.serializeAsVector3()
  19467. ], TransformNode.prototype, "position", void 0);
  19468. return TransformNode;
  19469. }(BABYLON.Node));
  19470. BABYLON.TransformNode = TransformNode;
  19471. })(BABYLON || (BABYLON = {}));
  19472. //# sourceMappingURL=babylon.transformNode.js.map
  19473. var BABYLON;
  19474. (function (BABYLON) {
  19475. /**
  19476. * Class used to store all common mesh properties
  19477. */
  19478. var AbstractMesh = /** @class */ (function (_super) {
  19479. __extends(AbstractMesh, _super);
  19480. // Constructor
  19481. /**
  19482. * Creates a new AbstractMesh
  19483. * @param name defines the name of the mesh
  19484. * @param scene defines the hosting scene
  19485. */
  19486. function AbstractMesh(name, scene) {
  19487. if (scene === void 0) { scene = null; }
  19488. var _this = _super.call(this, name, scene, false) || this;
  19489. _this._facetNb = 0; // facet number
  19490. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19491. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19492. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19493. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19494. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19495. _this._subDiv = {
  19496. max: 1,
  19497. X: 1,
  19498. Y: 1,
  19499. Z: 1
  19500. };
  19501. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19502. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19503. /** Gets ot sets the culling strategy to use to find visible meshes */
  19504. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19505. // Events
  19506. /**
  19507. * An event triggered when this mesh collides with another one
  19508. */
  19509. _this.onCollideObservable = new BABYLON.Observable();
  19510. /**
  19511. * An event triggered when the collision's position changes
  19512. */
  19513. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19514. /**
  19515. * An event triggered when material is changed
  19516. */
  19517. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19518. // Properties
  19519. /**
  19520. * Gets or sets the orientation for POV movement & rotation
  19521. */
  19522. _this.definedFacingForward = true;
  19523. /**
  19524. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19525. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19526. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19527. * @see http://doc.babylonjs.com/features/occlusionquery
  19528. */
  19529. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19530. /**
  19531. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19532. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19533. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19534. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19535. * @see http://doc.babylonjs.com/features/occlusionquery
  19536. */
  19537. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19538. /**
  19539. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19540. * The default value is -1 which means don't break the query and wait till the result
  19541. * @see http://doc.babylonjs.com/features/occlusionquery
  19542. */
  19543. _this.occlusionRetryCount = -1;
  19544. /** @hidden */
  19545. _this._occlusionInternalRetryCounter = 0;
  19546. /** @hidden */
  19547. _this._isOccluded = false;
  19548. /** @hidden */
  19549. _this._isOcclusionQueryInProgress = false;
  19550. _this._visibility = 1.0;
  19551. /** Gets or sets the alpha index used to sort transparent meshes
  19552. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19553. */
  19554. _this.alphaIndex = Number.MAX_VALUE;
  19555. /**
  19556. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19557. */
  19558. _this.isVisible = true;
  19559. /**
  19560. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19561. */
  19562. _this.isPickable = true;
  19563. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19564. _this.showSubMeshesBoundingBox = false;
  19565. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19566. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19567. */
  19568. _this.isBlocker = false;
  19569. /**
  19570. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19571. */
  19572. _this.enablePointerMoveEvents = false;
  19573. /**
  19574. * Specifies the rendering group id for this mesh (0 by default)
  19575. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19576. */
  19577. _this.renderingGroupId = 0;
  19578. _this._receiveShadows = false;
  19579. /**
  19580. * Gets or sets a boolean indicating if the outline must be rendered as well
  19581. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19582. */
  19583. _this.renderOutline = false;
  19584. /** Defines color to use when rendering outline */
  19585. _this.outlineColor = BABYLON.Color3.Red();
  19586. /** Define width to use when rendering outline */
  19587. _this.outlineWidth = 0.02;
  19588. /**
  19589. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19590. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19591. */
  19592. _this.renderOverlay = false;
  19593. /** Defines color to use when rendering overlay */
  19594. _this.overlayColor = BABYLON.Color3.Red();
  19595. /** Defines alpha to use when rendering overlay */
  19596. _this.overlayAlpha = 0.5;
  19597. _this._hasVertexAlpha = false;
  19598. _this._useVertexColors = true;
  19599. _this._computeBonesUsingShaders = true;
  19600. _this._numBoneInfluencers = 4;
  19601. _this._applyFog = true;
  19602. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19603. _this.useOctreeForRenderingSelection = true;
  19604. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19605. _this.useOctreeForPicking = true;
  19606. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19607. _this.useOctreeForCollisions = true;
  19608. _this._layerMask = 0x0FFFFFFF;
  19609. /**
  19610. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19611. */
  19612. _this.alwaysSelectAsActiveMesh = false;
  19613. /**
  19614. * Gets or sets the current action manager
  19615. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19616. */
  19617. _this.actionManager = null;
  19618. /**
  19619. * Gets or sets impostor used for physic simulation
  19620. * @see http://doc.babylonjs.com/features/physics_engine
  19621. */
  19622. _this.physicsImpostor = null;
  19623. // Collisions
  19624. _this._checkCollisions = false;
  19625. _this._collisionMask = -1;
  19626. _this._collisionGroup = -1;
  19627. /**
  19628. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19629. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19630. */
  19631. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19632. /**
  19633. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19634. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19635. */
  19636. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19637. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19638. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19639. // Edges
  19640. /**
  19641. * Defines edge width used when edgesRenderer is enabled
  19642. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19643. */
  19644. _this.edgesWidth = 1;
  19645. /**
  19646. * Defines edge color used when edgesRenderer is enabled
  19647. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19648. */
  19649. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19650. // Cache
  19651. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19652. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19653. /** @hidden */
  19654. _this._renderId = 0;
  19655. /** @hidden */
  19656. _this._intersectionsInProgress = new Array();
  19657. /** @hidden */
  19658. _this._unIndexed = false;
  19659. /** @hidden */
  19660. _this._lightSources = new Array();
  19661. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19662. if (collidedMesh === void 0) { collidedMesh = null; }
  19663. //TODO move this to the collision coordinator!
  19664. if (_this.getScene().workerCollisions)
  19665. newPosition.multiplyInPlace(_this._collider._radius);
  19666. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19667. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19668. _this.position.addInPlace(_this._diffPositionForCollisions);
  19669. }
  19670. if (collidedMesh) {
  19671. _this.onCollideObservable.notifyObservers(collidedMesh);
  19672. }
  19673. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19674. };
  19675. _this.getScene().addMesh(_this);
  19676. _this._resyncLightSources();
  19677. return _this;
  19678. }
  19679. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19680. /**
  19681. * No billboard
  19682. */
  19683. get: function () {
  19684. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19690. /** Billboard on X axis */
  19691. get: function () {
  19692. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19698. /** Billboard on Y axis */
  19699. get: function () {
  19700. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19706. /** Billboard on Z axis */
  19707. get: function () {
  19708. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19714. /** Billboard on all axes */
  19715. get: function () {
  19716. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19717. },
  19718. enumerable: true,
  19719. configurable: true
  19720. });
  19721. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19722. /**
  19723. * Gets the number of facets in the mesh
  19724. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19725. */
  19726. get: function () {
  19727. return this._facetNb;
  19728. },
  19729. enumerable: true,
  19730. configurable: true
  19731. });
  19732. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19733. /**
  19734. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19735. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19736. */
  19737. get: function () {
  19738. return this._partitioningSubdivisions;
  19739. },
  19740. set: function (nb) {
  19741. this._partitioningSubdivisions = nb;
  19742. },
  19743. enumerable: true,
  19744. configurable: true
  19745. });
  19746. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19747. /**
  19748. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19749. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19750. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19751. */
  19752. get: function () {
  19753. return this._partitioningBBoxRatio;
  19754. },
  19755. set: function (ratio) {
  19756. this._partitioningBBoxRatio = ratio;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19762. /**
  19763. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19764. * Works only for updatable meshes.
  19765. * Doesn't work with multi-materials
  19766. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19767. */
  19768. get: function () {
  19769. return this._facetDepthSort;
  19770. },
  19771. set: function (sort) {
  19772. this._facetDepthSort = sort;
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19778. /**
  19779. * The location (Vector3) where the facet depth sort must be computed from.
  19780. * By default, the active camera position.
  19781. * Used only when facet depth sort is enabled
  19782. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19783. */
  19784. get: function () {
  19785. return this._facetDepthSortFrom;
  19786. },
  19787. set: function (location) {
  19788. this._facetDepthSortFrom = location;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19794. /**
  19795. * gets a boolean indicating if facetData is enabled
  19796. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19797. */
  19798. get: function () {
  19799. return this._facetDataEnabled;
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. /** @hidden */
  19805. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19806. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19807. return false;
  19808. }
  19809. this._markSubMeshesAsMiscDirty();
  19810. return true;
  19811. };
  19812. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19813. /** Set a function to call when this mesh collides with another one */
  19814. set: function (callback) {
  19815. if (this._onCollideObserver) {
  19816. this.onCollideObservable.remove(this._onCollideObserver);
  19817. }
  19818. this._onCollideObserver = this.onCollideObservable.add(callback);
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19824. /** Set a function to call when the collision's position changes */
  19825. set: function (callback) {
  19826. if (this._onCollisionPositionChangeObserver) {
  19827. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19828. }
  19829. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19835. /**
  19836. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19837. * @see http://doc.babylonjs.com/features/occlusionquery
  19838. */
  19839. get: function () {
  19840. return this._isOccluded;
  19841. },
  19842. set: function (value) {
  19843. this._isOccluded = value;
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19849. /**
  19850. * Flag to check the progress status of the query
  19851. * @see http://doc.babylonjs.com/features/occlusionquery
  19852. */
  19853. get: function () {
  19854. return this._isOcclusionQueryInProgress;
  19855. },
  19856. enumerable: true,
  19857. configurable: true
  19858. });
  19859. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19860. /**
  19861. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19862. */
  19863. get: function () {
  19864. return this._visibility;
  19865. },
  19866. /**
  19867. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19868. */
  19869. set: function (value) {
  19870. if (this._visibility === value) {
  19871. return;
  19872. }
  19873. this._visibility = value;
  19874. this._markSubMeshesAsMiscDirty();
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(AbstractMesh.prototype, "material", {
  19880. /** Gets or sets current material */
  19881. get: function () {
  19882. return this._material;
  19883. },
  19884. set: function (value) {
  19885. if (this._material === value) {
  19886. return;
  19887. }
  19888. this._material = value;
  19889. if (this.onMaterialChangedObservable.hasObservers) {
  19890. this.onMaterialChangedObservable.notifyObservers(this);
  19891. }
  19892. if (!this.subMeshes) {
  19893. return;
  19894. }
  19895. this._unBindEffect();
  19896. },
  19897. enumerable: true,
  19898. configurable: true
  19899. });
  19900. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19901. /**
  19902. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19903. * @see http://doc.babylonjs.com/babylon101/shadows
  19904. */
  19905. get: function () {
  19906. return this._receiveShadows;
  19907. },
  19908. set: function (value) {
  19909. if (this._receiveShadows === value) {
  19910. return;
  19911. }
  19912. this._receiveShadows = value;
  19913. this._markSubMeshesAsLightDirty();
  19914. },
  19915. enumerable: true,
  19916. configurable: true
  19917. });
  19918. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19919. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19920. get: function () {
  19921. return this._hasVertexAlpha;
  19922. },
  19923. set: function (value) {
  19924. if (this._hasVertexAlpha === value) {
  19925. return;
  19926. }
  19927. this._hasVertexAlpha = value;
  19928. this._markSubMeshesAsAttributesDirty();
  19929. this._markSubMeshesAsMiscDirty();
  19930. },
  19931. enumerable: true,
  19932. configurable: true
  19933. });
  19934. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19935. /** 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) */
  19936. get: function () {
  19937. return this._useVertexColors;
  19938. },
  19939. set: function (value) {
  19940. if (this._useVertexColors === value) {
  19941. return;
  19942. }
  19943. this._useVertexColors = value;
  19944. this._markSubMeshesAsAttributesDirty();
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19950. /**
  19951. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19952. */
  19953. get: function () {
  19954. return this._computeBonesUsingShaders;
  19955. },
  19956. set: function (value) {
  19957. if (this._computeBonesUsingShaders === value) {
  19958. return;
  19959. }
  19960. this._computeBonesUsingShaders = value;
  19961. this._markSubMeshesAsAttributesDirty();
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19967. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19968. get: function () {
  19969. return this._numBoneInfluencers;
  19970. },
  19971. set: function (value) {
  19972. if (this._numBoneInfluencers === value) {
  19973. return;
  19974. }
  19975. this._numBoneInfluencers = value;
  19976. this._markSubMeshesAsAttributesDirty();
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19982. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19983. get: function () {
  19984. return this._applyFog;
  19985. },
  19986. set: function (value) {
  19987. if (this._applyFog === value) {
  19988. return;
  19989. }
  19990. this._applyFog = value;
  19991. this._markSubMeshesAsMiscDirty();
  19992. },
  19993. enumerable: true,
  19994. configurable: true
  19995. });
  19996. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19997. /**
  19998. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19999. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20000. */
  20001. get: function () {
  20002. return this._layerMask;
  20003. },
  20004. set: function (value) {
  20005. if (value === this._layerMask) {
  20006. return;
  20007. }
  20008. this._layerMask = value;
  20009. this._resyncLightSources();
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20015. /**
  20016. * Gets or sets a collision mask used to mask collisions (default is -1).
  20017. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20018. */
  20019. get: function () {
  20020. return this._collisionMask;
  20021. },
  20022. set: function (mask) {
  20023. this._collisionMask = !isNaN(mask) ? mask : -1;
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20029. /**
  20030. * Gets or sets the current collision group mask (-1 by default).
  20031. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20032. */
  20033. get: function () {
  20034. return this._collisionGroup;
  20035. },
  20036. set: function (mask) {
  20037. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20043. /** @hidden */
  20044. get: function () {
  20045. return null;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20051. get: function () {
  20052. return this._skeleton;
  20053. },
  20054. /**
  20055. * Gets or sets a skeleton to apply skining transformations
  20056. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20057. */
  20058. set: function (value) {
  20059. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20060. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20061. }
  20062. if (value && value.needInitialSkinMatrix) {
  20063. value._registerMeshWithPoseMatrix(this);
  20064. }
  20065. this._skeleton = value;
  20066. if (!this._skeleton) {
  20067. this._bonesTransformMatrices = null;
  20068. }
  20069. this._markSubMeshesAsAttributesDirty();
  20070. },
  20071. enumerable: true,
  20072. configurable: true
  20073. });
  20074. /**
  20075. * Returns the string "AbstractMesh"
  20076. * @returns "AbstractMesh"
  20077. */
  20078. AbstractMesh.prototype.getClassName = function () {
  20079. return "AbstractMesh";
  20080. };
  20081. /**
  20082. * Gets a string representation of the current mesh
  20083. * @param fullDetails defines a boolean indicating if full details must be included
  20084. * @returns a string representation of the current mesh
  20085. */
  20086. AbstractMesh.prototype.toString = function (fullDetails) {
  20087. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20088. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20089. if (this._skeleton) {
  20090. ret += ", skeleton: " + this._skeleton.name;
  20091. }
  20092. if (fullDetails) {
  20093. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20094. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20095. }
  20096. return ret;
  20097. };
  20098. /** @hidden */
  20099. AbstractMesh.prototype._rebuild = function () {
  20100. if (this._occlusionQuery) {
  20101. this._occlusionQuery = null;
  20102. }
  20103. if (this._edgesRenderer) {
  20104. this._edgesRenderer._rebuild();
  20105. }
  20106. if (!this.subMeshes) {
  20107. return;
  20108. }
  20109. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20110. var subMesh = _a[_i];
  20111. subMesh._rebuild();
  20112. }
  20113. };
  20114. /** @hidden */
  20115. AbstractMesh.prototype._resyncLightSources = function () {
  20116. this._lightSources.length = 0;
  20117. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20118. var light = _a[_i];
  20119. if (!light.isEnabled()) {
  20120. continue;
  20121. }
  20122. if (light.canAffectMesh(this)) {
  20123. this._lightSources.push(light);
  20124. }
  20125. }
  20126. this._markSubMeshesAsLightDirty();
  20127. };
  20128. /** @hidden */
  20129. AbstractMesh.prototype._resyncLighSource = function (light) {
  20130. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20131. var index = this._lightSources.indexOf(light);
  20132. if (index === -1) {
  20133. if (!isIn) {
  20134. return;
  20135. }
  20136. this._lightSources.push(light);
  20137. }
  20138. else {
  20139. if (isIn) {
  20140. return;
  20141. }
  20142. this._lightSources.splice(index, 1);
  20143. }
  20144. this._markSubMeshesAsLightDirty();
  20145. };
  20146. /** @hidden */
  20147. AbstractMesh.prototype._unBindEffect = function () {
  20148. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20149. var subMesh = _a[_i];
  20150. subMesh.setEffect(null);
  20151. }
  20152. };
  20153. /** @hidden */
  20154. AbstractMesh.prototype._removeLightSource = function (light) {
  20155. var index = this._lightSources.indexOf(light);
  20156. if (index === -1) {
  20157. return;
  20158. }
  20159. this._lightSources.splice(index, 1);
  20160. this._markSubMeshesAsLightDirty();
  20161. };
  20162. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20163. if (!this.subMeshes) {
  20164. return;
  20165. }
  20166. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20167. var subMesh = _a[_i];
  20168. if (subMesh._materialDefines) {
  20169. func(subMesh._materialDefines);
  20170. }
  20171. }
  20172. };
  20173. /** @hidden */
  20174. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20175. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20176. };
  20177. /** @hidden */
  20178. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20179. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20180. };
  20181. /** @hidden */
  20182. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20183. if (!this.subMeshes) {
  20184. return;
  20185. }
  20186. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20187. var subMesh = _a[_i];
  20188. var material = subMesh.getMaterial();
  20189. if (material) {
  20190. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20191. }
  20192. }
  20193. };
  20194. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20195. /**
  20196. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20197. */
  20198. get: function () {
  20199. return this._scaling;
  20200. },
  20201. set: function (newScaling) {
  20202. this._scaling = newScaling;
  20203. if (this.physicsImpostor) {
  20204. this.physicsImpostor.forceUpdate();
  20205. }
  20206. },
  20207. enumerable: true,
  20208. configurable: true
  20209. });
  20210. // Methods
  20211. /**
  20212. * Disables the mesh edge rendering mode
  20213. * @returns the currentAbstractMesh
  20214. */
  20215. AbstractMesh.prototype.disableEdgesRendering = function () {
  20216. if (this._edgesRenderer) {
  20217. this._edgesRenderer.dispose();
  20218. this._edgesRenderer = null;
  20219. }
  20220. return this;
  20221. };
  20222. /**
  20223. * Enables the edge rendering mode on the mesh.
  20224. * This mode makes the mesh edges visible
  20225. * @param epsilon defines the maximal distance between two angles to detect a face
  20226. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20227. * @returns the currentAbstractMesh
  20228. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20229. */
  20230. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20231. if (epsilon === void 0) { epsilon = 0.95; }
  20232. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20233. this.disableEdgesRendering();
  20234. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20235. return this;
  20236. };
  20237. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20238. /**
  20239. * Gets the edgesRenderer associated with the mesh
  20240. */
  20241. get: function () {
  20242. return this._edgesRenderer;
  20243. },
  20244. enumerable: true,
  20245. configurable: true
  20246. });
  20247. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20248. /**
  20249. * Returns true if the mesh is blocked. Implemented by child classes
  20250. */
  20251. get: function () {
  20252. return false;
  20253. },
  20254. enumerable: true,
  20255. configurable: true
  20256. });
  20257. /**
  20258. * Returns the mesh itself by default. Implemented by child classes
  20259. * @param camera defines the camera to use to pick the right LOD level
  20260. * @returns the currentAbstractMesh
  20261. */
  20262. AbstractMesh.prototype.getLOD = function (camera) {
  20263. return this;
  20264. };
  20265. /**
  20266. * Returns 0 by default. Implemented by child classes
  20267. * @returns an integer
  20268. */
  20269. AbstractMesh.prototype.getTotalVertices = function () {
  20270. return 0;
  20271. };
  20272. /**
  20273. * Returns null by default. Implemented by child classes
  20274. * @returns null
  20275. */
  20276. AbstractMesh.prototype.getIndices = function () {
  20277. return null;
  20278. };
  20279. /**
  20280. * Returns the array of the requested vertex data kind. Implemented by child classes
  20281. * @param kind defines the vertex data kind to use
  20282. * @returns null
  20283. */
  20284. AbstractMesh.prototype.getVerticesData = function (kind) {
  20285. return null;
  20286. };
  20287. /**
  20288. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20289. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20290. * Note that a new underlying VertexBuffer object is created each call.
  20291. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20292. * @param kind defines vertex data kind:
  20293. * * BABYLON.VertexBuffer.PositionKind
  20294. * * BABYLON.VertexBuffer.UVKind
  20295. * * BABYLON.VertexBuffer.UV2Kind
  20296. * * BABYLON.VertexBuffer.UV3Kind
  20297. * * BABYLON.VertexBuffer.UV4Kind
  20298. * * BABYLON.VertexBuffer.UV5Kind
  20299. * * BABYLON.VertexBuffer.UV6Kind
  20300. * * BABYLON.VertexBuffer.ColorKind
  20301. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20302. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20303. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20304. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20305. * @param data defines the data source
  20306. * @param updatable defines if the data must be flagged as updatable (or static)
  20307. * @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
  20308. * @returns the current mesh
  20309. */
  20310. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20311. return this;
  20312. };
  20313. /**
  20314. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20315. * If the mesh has no geometry, it is simply returned as it is.
  20316. * @param kind defines vertex data kind:
  20317. * * BABYLON.VertexBuffer.PositionKind
  20318. * * BABYLON.VertexBuffer.UVKind
  20319. * * BABYLON.VertexBuffer.UV2Kind
  20320. * * BABYLON.VertexBuffer.UV3Kind
  20321. * * BABYLON.VertexBuffer.UV4Kind
  20322. * * BABYLON.VertexBuffer.UV5Kind
  20323. * * BABYLON.VertexBuffer.UV6Kind
  20324. * * BABYLON.VertexBuffer.ColorKind
  20325. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20326. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20327. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20328. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20329. * @param data defines the data source
  20330. * @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
  20331. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20332. * @returns the current mesh
  20333. */
  20334. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20335. return this;
  20336. };
  20337. /**
  20338. * Sets the mesh indices,
  20339. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20340. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20341. * @param totalVertices Defines the total number of vertices
  20342. * @returns the current mesh
  20343. */
  20344. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20345. return this;
  20346. };
  20347. /**
  20348. * Gets a boolean indicating if specific vertex data is present
  20349. * @param kind defines the vertex data kind to use
  20350. * @returns true is data kind is present
  20351. */
  20352. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20353. return false;
  20354. };
  20355. /**
  20356. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20357. * @returns a BoundingInfo
  20358. */
  20359. AbstractMesh.prototype.getBoundingInfo = function () {
  20360. if (this._masterMesh) {
  20361. return this._masterMesh.getBoundingInfo();
  20362. }
  20363. if (!this._boundingInfo) {
  20364. // this._boundingInfo is being created here
  20365. this._updateBoundingInfo();
  20366. }
  20367. // cannot be null.
  20368. return this._boundingInfo;
  20369. };
  20370. /**
  20371. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20372. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20373. * @returns the current mesh
  20374. */
  20375. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20376. if (includeDescendants === void 0) { includeDescendants = true; }
  20377. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20378. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20379. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20380. if (maxDimension === 0) {
  20381. return this;
  20382. }
  20383. var scale = 1 / maxDimension;
  20384. this.scaling.scaleInPlace(scale);
  20385. return this;
  20386. };
  20387. /**
  20388. * Overwrite the current bounding info
  20389. * @param boundingInfo defines the new bounding info
  20390. * @returns the current mesh
  20391. */
  20392. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20393. this._boundingInfo = boundingInfo;
  20394. return this;
  20395. };
  20396. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20397. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20398. get: function () {
  20399. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20400. },
  20401. enumerable: true,
  20402. configurable: true
  20403. });
  20404. /** @hidden */
  20405. AbstractMesh.prototype._preActivate = function () {
  20406. };
  20407. /** @hidden */
  20408. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20409. };
  20410. /** @hidden */
  20411. AbstractMesh.prototype._activate = function (renderId) {
  20412. this._renderId = renderId;
  20413. };
  20414. /**
  20415. * Gets the current world matrix
  20416. * @returns a Matrix
  20417. */
  20418. AbstractMesh.prototype.getWorldMatrix = function () {
  20419. if (this._masterMesh) {
  20420. return this._masterMesh.getWorldMatrix();
  20421. }
  20422. return _super.prototype.getWorldMatrix.call(this);
  20423. };
  20424. /** @hidden */
  20425. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20426. if (this._masterMesh) {
  20427. return this._masterMesh._getWorldMatrixDeterminant();
  20428. }
  20429. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20430. };
  20431. // ================================== Point of View Movement =================================
  20432. /**
  20433. * Perform relative position change from the point of view of behind the front of the mesh.
  20434. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20435. * Supports definition of mesh facing forward or backward
  20436. * @param amountRight defines the distance on the right axis
  20437. * @param amountUp defines the distance on the up axis
  20438. * @param amountForward defines the distance on the forward axis
  20439. * @returns the current mesh
  20440. */
  20441. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20442. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20443. return this;
  20444. };
  20445. /**
  20446. * Calculate relative position change from the point of view of behind the front of the mesh.
  20447. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20448. * Supports definition of mesh facing forward or backward
  20449. * @param amountRight defines the distance on the right axis
  20450. * @param amountUp defines the distance on the up axis
  20451. * @param amountForward defines the distance on the forward axis
  20452. * @returns the new displacement vector
  20453. */
  20454. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20455. var rotMatrix = new BABYLON.Matrix();
  20456. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20457. rotQuaternion.toRotationMatrix(rotMatrix);
  20458. var translationDelta = BABYLON.Vector3.Zero();
  20459. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20460. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20461. return translationDelta;
  20462. };
  20463. // ================================== Point of View Rotation =================================
  20464. /**
  20465. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20466. * Supports definition of mesh facing forward or backward
  20467. * @param flipBack defines the flip
  20468. * @param twirlClockwise defines the twirl
  20469. * @param tiltRight defines the tilt
  20470. * @returns the current mesh
  20471. */
  20472. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20473. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20474. return this;
  20475. };
  20476. /**
  20477. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20478. * Supports definition of mesh facing forward or backward.
  20479. * @param flipBack defines the flip
  20480. * @param twirlClockwise defines the twirl
  20481. * @param tiltRight defines the tilt
  20482. * @returns the new rotation vector
  20483. */
  20484. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20485. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20486. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20487. };
  20488. /**
  20489. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20490. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20491. * @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
  20492. * @returns the new bounding vectors
  20493. */
  20494. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20495. if (includeDescendants === void 0) { includeDescendants = true; }
  20496. if (predicate === void 0) { predicate = null; }
  20497. // Ensures that all world matrix will be recomputed.
  20498. this.getScene().incrementRenderId();
  20499. this.computeWorldMatrix(true);
  20500. var min;
  20501. var max;
  20502. var boundingInfo = this.getBoundingInfo();
  20503. if (!this.subMeshes) {
  20504. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20505. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20506. }
  20507. else {
  20508. min = boundingInfo.boundingBox.minimumWorld;
  20509. max = boundingInfo.boundingBox.maximumWorld;
  20510. }
  20511. if (includeDescendants) {
  20512. var descendants = this.getDescendants(false);
  20513. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20514. var descendant = descendants_1[_i];
  20515. var childMesh = descendant;
  20516. childMesh.computeWorldMatrix(true);
  20517. // Filters meshes based on custom predicate function.
  20518. if (predicate && !predicate(childMesh)) {
  20519. continue;
  20520. }
  20521. //make sure we have the needed params to get mix and max
  20522. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20523. continue;
  20524. }
  20525. var childBoundingInfo = childMesh.getBoundingInfo();
  20526. var boundingBox = childBoundingInfo.boundingBox;
  20527. var minBox = boundingBox.minimumWorld;
  20528. var maxBox = boundingBox.maximumWorld;
  20529. BABYLON.Tools.CheckExtends(minBox, min, max);
  20530. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20531. }
  20532. }
  20533. return {
  20534. min: min,
  20535. max: max
  20536. };
  20537. };
  20538. /** @hidden */
  20539. AbstractMesh.prototype._updateBoundingInfo = function () {
  20540. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20541. this._boundingInfo.update(this.worldMatrixFromCache);
  20542. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20543. return this;
  20544. };
  20545. /** @hidden */
  20546. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20547. if (!this.subMeshes) {
  20548. return this;
  20549. }
  20550. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20551. var subMesh = this.subMeshes[subIndex];
  20552. if (!subMesh.IsGlobal) {
  20553. subMesh.updateBoundingInfo(matrix);
  20554. }
  20555. }
  20556. return this;
  20557. };
  20558. /** @hidden */
  20559. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20560. // Bounding info
  20561. this._updateBoundingInfo();
  20562. };
  20563. /**
  20564. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20565. * A mesh is in the frustum if its bounding box intersects the frustum
  20566. * @param frustumPlanes defines the frustum to test
  20567. * @returns true if the mesh is in the frustum planes
  20568. */
  20569. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20570. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20571. };
  20572. /**
  20573. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20574. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20575. * @param frustumPlanes defines the frustum to test
  20576. * @returns true if the mesh is completely in the frustum planes
  20577. */
  20578. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20579. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20580. };
  20581. /**
  20582. * True if the mesh intersects another mesh or a SolidParticle object
  20583. * @param mesh defines a target mesh or SolidParticle to test
  20584. * @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)
  20585. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20586. * @returns true if there is an intersection
  20587. */
  20588. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20589. if (precise === void 0) { precise = false; }
  20590. if (!this._boundingInfo || !mesh._boundingInfo) {
  20591. return false;
  20592. }
  20593. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20594. return true;
  20595. }
  20596. if (includeDescendants) {
  20597. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20598. var child = _a[_i];
  20599. if (child.intersectsMesh(mesh, precise, true)) {
  20600. return true;
  20601. }
  20602. }
  20603. }
  20604. return false;
  20605. };
  20606. /**
  20607. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20608. * @param point defines the point to test
  20609. * @returns true if there is an intersection
  20610. */
  20611. AbstractMesh.prototype.intersectsPoint = function (point) {
  20612. if (!this._boundingInfo) {
  20613. return false;
  20614. }
  20615. return this._boundingInfo.intersectsPoint(point);
  20616. };
  20617. /**
  20618. * Gets the current physics impostor
  20619. * @see http://doc.babylonjs.com/features/physics_engine
  20620. * @returns a physics impostor or null
  20621. */
  20622. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20623. return this.physicsImpostor;
  20624. };
  20625. /**
  20626. * Gets the position of the current mesh in camera space
  20627. * @param camera defines the camera to use
  20628. * @returns a position
  20629. */
  20630. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20631. if (camera === void 0) { camera = null; }
  20632. if (!camera) {
  20633. camera = this.getScene().activeCamera;
  20634. }
  20635. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20636. };
  20637. /**
  20638. * Returns the distance from the mesh to the active camera
  20639. * @param camera defines the camera to use
  20640. * @returns the distance
  20641. */
  20642. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20643. if (camera === void 0) { camera = null; }
  20644. if (!camera) {
  20645. camera = this.getScene().activeCamera;
  20646. }
  20647. return this.absolutePosition.subtract(camera.position).length();
  20648. };
  20649. /**
  20650. * Apply a physic impulse to the mesh
  20651. * @param force defines the force to apply
  20652. * @param contactPoint defines where to apply the force
  20653. * @returns the current mesh
  20654. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20655. */
  20656. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20657. if (!this.physicsImpostor) {
  20658. return this;
  20659. }
  20660. this.physicsImpostor.applyImpulse(force, contactPoint);
  20661. return this;
  20662. };
  20663. /**
  20664. * Creates a physic joint between two meshes
  20665. * @param otherMesh defines the other mesh to use
  20666. * @param pivot1 defines the pivot to use on this mesh
  20667. * @param pivot2 defines the pivot to use on the other mesh
  20668. * @param options defines additional options (can be plugin dependent)
  20669. * @returns the current mesh
  20670. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20671. */
  20672. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20673. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20674. return this;
  20675. }
  20676. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20677. mainPivot: pivot1,
  20678. connectedPivot: pivot2,
  20679. nativeParams: options
  20680. });
  20681. return this;
  20682. };
  20683. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20684. // Collisions
  20685. /**
  20686. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20687. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20688. */
  20689. get: function () {
  20690. return this._checkCollisions;
  20691. },
  20692. set: function (collisionEnabled) {
  20693. this._checkCollisions = collisionEnabled;
  20694. if (this.getScene().workerCollisions) {
  20695. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20696. }
  20697. },
  20698. enumerable: true,
  20699. configurable: true
  20700. });
  20701. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20702. /**
  20703. * Gets Collider object used to compute collisions (not physics)
  20704. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20705. */
  20706. get: function () {
  20707. return this._collider;
  20708. },
  20709. enumerable: true,
  20710. configurable: true
  20711. });
  20712. /**
  20713. * Move the mesh using collision engine
  20714. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20715. * @param displacement defines the requested displacement vector
  20716. * @returns the current mesh
  20717. */
  20718. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20719. var globalPosition = this.getAbsolutePosition();
  20720. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20721. if (!this._collider) {
  20722. this._collider = new BABYLON.Collider();
  20723. }
  20724. this._collider._radius = this.ellipsoid;
  20725. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20726. return this;
  20727. };
  20728. // Submeshes octree
  20729. /**
  20730. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20731. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20732. * @param maxCapacity defines the maximum size of each block (64 by default)
  20733. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20734. * @returns the new octree
  20735. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20736. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20737. */
  20738. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20739. if (maxCapacity === void 0) { maxCapacity = 64; }
  20740. if (maxDepth === void 0) { maxDepth = 2; }
  20741. if (!this._submeshesOctree) {
  20742. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20743. }
  20744. this.computeWorldMatrix(true);
  20745. var boundingInfo = this.getBoundingInfo();
  20746. // Update octree
  20747. var bbox = boundingInfo.boundingBox;
  20748. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20749. return this._submeshesOctree;
  20750. };
  20751. // Collisions
  20752. /** @hidden */
  20753. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20754. this._generatePointsArray();
  20755. if (!this._positions) {
  20756. return this;
  20757. }
  20758. // Transformation
  20759. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20760. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20761. subMesh._lastColliderWorldVertices = [];
  20762. subMesh._trianglePlanes = [];
  20763. var start = subMesh.verticesStart;
  20764. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20765. for (var i = start; i < end; i++) {
  20766. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20767. }
  20768. }
  20769. // Collide
  20770. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20771. if (collider.collisionFound) {
  20772. collider.collidedMesh = this;
  20773. }
  20774. return this;
  20775. };
  20776. /** @hidden */
  20777. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20778. var subMeshes;
  20779. var len;
  20780. // Octrees
  20781. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20782. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20783. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20784. len = intersections.length;
  20785. subMeshes = intersections.data;
  20786. }
  20787. else {
  20788. subMeshes = this.subMeshes;
  20789. len = subMeshes.length;
  20790. }
  20791. for (var index = 0; index < len; index++) {
  20792. var subMesh = subMeshes[index];
  20793. // Bounding test
  20794. if (len > 1 && !subMesh._checkCollision(collider))
  20795. continue;
  20796. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20797. }
  20798. return this;
  20799. };
  20800. /** @hidden */
  20801. AbstractMesh.prototype._checkCollision = function (collider) {
  20802. // Bounding box test
  20803. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20804. return this;
  20805. // Transformation matrix
  20806. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20807. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20808. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20809. return this;
  20810. };
  20811. // Picking
  20812. /** @hidden */
  20813. AbstractMesh.prototype._generatePointsArray = function () {
  20814. return false;
  20815. };
  20816. /**
  20817. * Checks if the passed Ray intersects with the mesh
  20818. * @param ray defines the ray to use
  20819. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20820. * @returns the picking info
  20821. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20822. */
  20823. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20824. var pickingInfo = new BABYLON.PickingInfo();
  20825. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20826. return pickingInfo;
  20827. }
  20828. if (!this._generatePointsArray()) {
  20829. return pickingInfo;
  20830. }
  20831. var intersectInfo = null;
  20832. // Octrees
  20833. var subMeshes;
  20834. var len;
  20835. if (this._submeshesOctree && this.useOctreeForPicking) {
  20836. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20837. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20838. len = intersections.length;
  20839. subMeshes = intersections.data;
  20840. }
  20841. else {
  20842. subMeshes = this.subMeshes;
  20843. len = subMeshes.length;
  20844. }
  20845. for (var index = 0; index < len; index++) {
  20846. var subMesh = subMeshes[index];
  20847. // Bounding test
  20848. if (len > 1 && !subMesh.canIntersects(ray))
  20849. continue;
  20850. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20851. if (currentIntersectInfo) {
  20852. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20853. intersectInfo = currentIntersectInfo;
  20854. intersectInfo.subMeshId = index;
  20855. if (fastCheck) {
  20856. break;
  20857. }
  20858. }
  20859. }
  20860. }
  20861. if (intersectInfo) {
  20862. // Get picked point
  20863. var world = this.getWorldMatrix();
  20864. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20865. var direction = ray.direction.clone();
  20866. direction = direction.scale(intersectInfo.distance);
  20867. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20868. var pickedPoint = worldOrigin.add(worldDirection);
  20869. // Return result
  20870. pickingInfo.hit = true;
  20871. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20872. pickingInfo.pickedPoint = pickedPoint;
  20873. pickingInfo.pickedMesh = this;
  20874. pickingInfo.bu = intersectInfo.bu || 0;
  20875. pickingInfo.bv = intersectInfo.bv || 0;
  20876. pickingInfo.faceId = intersectInfo.faceId;
  20877. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20878. return pickingInfo;
  20879. }
  20880. return pickingInfo;
  20881. };
  20882. /**
  20883. * Clones the current mesh
  20884. * @param name defines the mesh name
  20885. * @param newParent defines the new mesh parent
  20886. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20887. * @returns the new mesh
  20888. */
  20889. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20890. return null;
  20891. };
  20892. /**
  20893. * Disposes all the submeshes of the current meshnp
  20894. * @returns the current mesh
  20895. */
  20896. AbstractMesh.prototype.releaseSubMeshes = function () {
  20897. if (this.subMeshes) {
  20898. while (this.subMeshes.length) {
  20899. this.subMeshes[0].dispose();
  20900. }
  20901. }
  20902. else {
  20903. this.subMeshes = new Array();
  20904. }
  20905. return this;
  20906. };
  20907. /**
  20908. * Releases resources associated with this abstract mesh.
  20909. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20910. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20911. */
  20912. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20913. var _this = this;
  20914. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20915. var index;
  20916. // Smart Array Retainers.
  20917. this.getScene().freeActiveMeshes();
  20918. this.getScene().freeRenderingGroups();
  20919. // Action manager
  20920. if (this.actionManager !== undefined && this.actionManager !== null) {
  20921. this.actionManager.dispose();
  20922. this.actionManager = null;
  20923. }
  20924. // Skeleton
  20925. this._skeleton = null;
  20926. // Physics
  20927. if (this.physicsImpostor) {
  20928. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20929. }
  20930. // Intersections in progress
  20931. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20932. var other = this._intersectionsInProgress[index];
  20933. var pos = other._intersectionsInProgress.indexOf(this);
  20934. other._intersectionsInProgress.splice(pos, 1);
  20935. }
  20936. this._intersectionsInProgress = [];
  20937. // Lights
  20938. var lights = this.getScene().lights;
  20939. lights.forEach(function (light) {
  20940. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20941. if (meshIndex !== -1) {
  20942. light.includedOnlyMeshes.splice(meshIndex, 1);
  20943. }
  20944. meshIndex = light.excludedMeshes.indexOf(_this);
  20945. if (meshIndex !== -1) {
  20946. light.excludedMeshes.splice(meshIndex, 1);
  20947. }
  20948. // Shadow generators
  20949. var generator = light.getShadowGenerator();
  20950. if (generator) {
  20951. var shadowMap = generator.getShadowMap();
  20952. if (shadowMap && shadowMap.renderList) {
  20953. meshIndex = shadowMap.renderList.indexOf(_this);
  20954. if (meshIndex !== -1) {
  20955. shadowMap.renderList.splice(meshIndex, 1);
  20956. }
  20957. }
  20958. }
  20959. });
  20960. // Edges
  20961. if (this._edgesRenderer) {
  20962. this._edgesRenderer.dispose();
  20963. this._edgesRenderer = null;
  20964. }
  20965. // SubMeshes
  20966. if (this.getClassName() !== "InstancedMesh") {
  20967. this.releaseSubMeshes();
  20968. }
  20969. // Octree
  20970. var sceneOctree = this.getScene().selectionOctree;
  20971. if (sceneOctree !== undefined && sceneOctree !== null) {
  20972. var index = sceneOctree.dynamicContent.indexOf(this);
  20973. if (index !== -1) {
  20974. sceneOctree.dynamicContent.splice(index, 1);
  20975. }
  20976. }
  20977. // Query
  20978. var engine = this.getScene().getEngine();
  20979. if (this._occlusionQuery) {
  20980. this._isOcclusionQueryInProgress = false;
  20981. engine.deleteQuery(this._occlusionQuery);
  20982. this._occlusionQuery = null;
  20983. }
  20984. // Engine
  20985. engine.wipeCaches();
  20986. // Remove from scene
  20987. this.getScene().removeMesh(this);
  20988. if (disposeMaterialAndTextures) {
  20989. if (this.material) {
  20990. this.material.dispose(false, true);
  20991. }
  20992. }
  20993. if (!doNotRecurse) {
  20994. // Particles
  20995. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20996. if (this.getScene().particleSystems[index].emitter === this) {
  20997. this.getScene().particleSystems[index].dispose();
  20998. index--;
  20999. }
  21000. }
  21001. }
  21002. // facet data
  21003. if (this._facetDataEnabled) {
  21004. this.disableFacetData();
  21005. }
  21006. this.onAfterWorldMatrixUpdateObservable.clear();
  21007. this.onCollideObservable.clear();
  21008. this.onCollisionPositionChangeObservable.clear();
  21009. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21010. };
  21011. /**
  21012. * Adds the passed mesh as a child to the current mesh
  21013. * @param mesh defines the child mesh
  21014. * @returns the current mesh
  21015. */
  21016. AbstractMesh.prototype.addChild = function (mesh) {
  21017. mesh.setParent(this);
  21018. return this;
  21019. };
  21020. /**
  21021. * Removes the passed mesh from the current mesh children list
  21022. * @param mesh defines the child mesh
  21023. * @returns the current mesh
  21024. */
  21025. AbstractMesh.prototype.removeChild = function (mesh) {
  21026. mesh.setParent(null);
  21027. return this;
  21028. };
  21029. // Facet data
  21030. /** @hidden */
  21031. AbstractMesh.prototype._initFacetData = function () {
  21032. if (!this._facetNormals) {
  21033. this._facetNormals = new Array();
  21034. }
  21035. if (!this._facetPositions) {
  21036. this._facetPositions = new Array();
  21037. }
  21038. if (!this._facetPartitioning) {
  21039. this._facetPartitioning = new Array();
  21040. }
  21041. this._facetNb = (this.getIndices().length / 3) | 0;
  21042. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21043. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21044. for (var f = 0; f < this._facetNb; f++) {
  21045. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21046. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21047. }
  21048. this._facetDataEnabled = true;
  21049. return this;
  21050. };
  21051. /**
  21052. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21053. * This method can be called within the render loop.
  21054. * 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
  21055. * @returns the current mesh
  21056. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21057. */
  21058. AbstractMesh.prototype.updateFacetData = function () {
  21059. if (!this._facetDataEnabled) {
  21060. this._initFacetData();
  21061. }
  21062. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21063. var indices = this.getIndices();
  21064. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21065. var bInfo = this.getBoundingInfo();
  21066. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21067. // init arrays, matrix and sort function on first call
  21068. this._facetDepthSortEnabled = true;
  21069. if (indices instanceof Uint16Array) {
  21070. this._depthSortedIndices = new Uint16Array(indices);
  21071. }
  21072. else if (indices instanceof Uint32Array) {
  21073. this._depthSortedIndices = new Uint32Array(indices);
  21074. }
  21075. else {
  21076. var needs32bits = false;
  21077. for (var i = 0; i < indices.length; i++) {
  21078. if (indices[i] > 65535) {
  21079. needs32bits = true;
  21080. break;
  21081. }
  21082. }
  21083. if (needs32bits) {
  21084. this._depthSortedIndices = new Uint32Array(indices);
  21085. }
  21086. else {
  21087. this._depthSortedIndices = new Uint16Array(indices);
  21088. }
  21089. }
  21090. this._facetDepthSortFunction = function (f1, f2) {
  21091. return (f2.sqDistance - f1.sqDistance);
  21092. };
  21093. if (!this._facetDepthSortFrom) {
  21094. var camera = this.getScene().activeCamera;
  21095. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21096. }
  21097. this._depthSortedFacets = [];
  21098. for (var f = 0; f < this._facetNb; f++) {
  21099. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21100. this._depthSortedFacets.push(depthSortedFacet);
  21101. }
  21102. this._invertedMatrix = BABYLON.Matrix.Identity();
  21103. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21104. }
  21105. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21106. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21107. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21108. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21109. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21110. this._subDiv.max = this._partitioningSubdivisions;
  21111. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21112. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21113. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21114. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21115. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21116. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21117. // set the parameters for ComputeNormals()
  21118. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21119. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21120. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21121. this._facetParameters.bInfo = bInfo;
  21122. this._facetParameters.bbSize = this._bbSize;
  21123. this._facetParameters.subDiv = this._subDiv;
  21124. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21125. this._facetParameters.depthSort = this._facetDepthSort;
  21126. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21127. this.computeWorldMatrix(true);
  21128. this._worldMatrix.invertToRef(this._invertedMatrix);
  21129. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21130. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21131. }
  21132. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21133. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21134. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21135. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21136. var l = (this._depthSortedIndices.length / 3) | 0;
  21137. for (var f = 0; f < l; f++) {
  21138. var sind = this._depthSortedFacets[f].ind;
  21139. this._depthSortedIndices[f * 3] = indices[sind];
  21140. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21141. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21142. }
  21143. this.updateIndices(this._depthSortedIndices);
  21144. }
  21145. return this;
  21146. };
  21147. /**
  21148. * Returns the facetLocalNormals array.
  21149. * The normals are expressed in the mesh local spac
  21150. * @returns an array of Vector3
  21151. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21152. */
  21153. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21154. if (!this._facetNormals) {
  21155. this.updateFacetData();
  21156. }
  21157. return this._facetNormals;
  21158. };
  21159. /**
  21160. * Returns the facetLocalPositions array.
  21161. * The facet positions are expressed in the mesh local space
  21162. * @returns an array of Vector3
  21163. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21164. */
  21165. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21166. if (!this._facetPositions) {
  21167. this.updateFacetData();
  21168. }
  21169. return this._facetPositions;
  21170. };
  21171. /**
  21172. * Returns the facetLocalPartioning array
  21173. * @returns an array of array of numbers
  21174. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21175. */
  21176. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21177. if (!this._facetPartitioning) {
  21178. this.updateFacetData();
  21179. }
  21180. return this._facetPartitioning;
  21181. };
  21182. /**
  21183. * Returns the i-th facet position in the world system.
  21184. * This method allocates a new Vector3 per call
  21185. * @param i defines the facet index
  21186. * @returns a new Vector3
  21187. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21188. */
  21189. AbstractMesh.prototype.getFacetPosition = function (i) {
  21190. var pos = BABYLON.Vector3.Zero();
  21191. this.getFacetPositionToRef(i, pos);
  21192. return pos;
  21193. };
  21194. /**
  21195. * Sets the reference Vector3 with the i-th facet position in the world system
  21196. * @param i defines the facet index
  21197. * @param ref defines the target vector
  21198. * @returns the current mesh
  21199. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21200. */
  21201. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21202. var localPos = (this.getFacetLocalPositions())[i];
  21203. var world = this.getWorldMatrix();
  21204. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21205. return this;
  21206. };
  21207. /**
  21208. * Returns the i-th facet normal in the world system.
  21209. * This method allocates a new Vector3 per call
  21210. * @param i defines the facet index
  21211. * @returns a new Vector3
  21212. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21213. */
  21214. AbstractMesh.prototype.getFacetNormal = function (i) {
  21215. var norm = BABYLON.Vector3.Zero();
  21216. this.getFacetNormalToRef(i, norm);
  21217. return norm;
  21218. };
  21219. /**
  21220. * Sets the reference Vector3 with the i-th facet normal in the world system
  21221. * @param i defines the facet index
  21222. * @param ref defines the target vector
  21223. * @returns the current mesh
  21224. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21225. */
  21226. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21227. var localNorm = (this.getFacetLocalNormals())[i];
  21228. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21229. return this;
  21230. };
  21231. /**
  21232. * 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)
  21233. * @param x defines x coordinate
  21234. * @param y defines y coordinate
  21235. * @param z defines z coordinate
  21236. * @returns the array of facet indexes
  21237. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21238. */
  21239. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21240. var bInfo = this.getBoundingInfo();
  21241. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21242. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21243. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21244. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21245. return null;
  21246. }
  21247. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21248. };
  21249. /**
  21250. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21251. * @param projected sets as the (x,y,z) world projection on the facet
  21252. * @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
  21253. * @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
  21254. * @param x defines x coordinate
  21255. * @param y defines y coordinate
  21256. * @param z defines z coordinate
  21257. * @returns the face index if found (or null instead)
  21258. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21259. */
  21260. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21261. if (checkFace === void 0) { checkFace = false; }
  21262. if (facing === void 0) { facing = true; }
  21263. var world = this.getWorldMatrix();
  21264. var invMat = BABYLON.Tmp.Matrix[5];
  21265. world.invertToRef(invMat);
  21266. var invVect = BABYLON.Tmp.Vector3[8];
  21267. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21268. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21269. if (projected) {
  21270. // tranform the local computed projected vector to world coordinates
  21271. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21272. }
  21273. return closest;
  21274. };
  21275. /**
  21276. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21277. * @param projected sets as the (x,y,z) local projection on the facet
  21278. * @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
  21279. * @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
  21280. * @param x defines x coordinate
  21281. * @param y defines y coordinate
  21282. * @param z defines z coordinate
  21283. * @returns the face index if found (or null instead)
  21284. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21285. */
  21286. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21287. if (checkFace === void 0) { checkFace = false; }
  21288. if (facing === void 0) { facing = true; }
  21289. var closest = null;
  21290. var tmpx = 0.0;
  21291. var tmpy = 0.0;
  21292. var tmpz = 0.0;
  21293. var d = 0.0; // tmp dot facet normal * facet position
  21294. var t0 = 0.0;
  21295. var projx = 0.0;
  21296. var projy = 0.0;
  21297. var projz = 0.0;
  21298. // Get all the facets in the same partitioning block than (x, y, z)
  21299. var facetPositions = this.getFacetLocalPositions();
  21300. var facetNormals = this.getFacetLocalNormals();
  21301. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21302. if (!facetsInBlock) {
  21303. return null;
  21304. }
  21305. // Get the closest facet to (x, y, z)
  21306. var shortest = Number.MAX_VALUE; // init distance vars
  21307. var tmpDistance = shortest;
  21308. var fib; // current facet in the block
  21309. var norm; // current facet normal
  21310. var p0; // current facet barycenter position
  21311. // loop on all the facets in the current partitioning block
  21312. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21313. fib = facetsInBlock[idx];
  21314. norm = facetNormals[fib];
  21315. p0 = facetPositions[fib];
  21316. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21317. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21318. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21319. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21320. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21321. projx = x + norm.x * t0;
  21322. projy = y + norm.y * t0;
  21323. projz = z + norm.z * t0;
  21324. tmpx = projx - x;
  21325. tmpy = projy - y;
  21326. tmpz = projz - z;
  21327. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21328. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21329. shortest = tmpDistance;
  21330. closest = fib;
  21331. if (projected) {
  21332. projected.x = projx;
  21333. projected.y = projy;
  21334. projected.z = projz;
  21335. }
  21336. }
  21337. }
  21338. }
  21339. return closest;
  21340. };
  21341. /**
  21342. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21343. * @returns the parameters
  21344. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21345. */
  21346. AbstractMesh.prototype.getFacetDataParameters = function () {
  21347. return this._facetParameters;
  21348. };
  21349. /**
  21350. * Disables the feature FacetData and frees the related memory
  21351. * @returns the current mesh
  21352. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21353. */
  21354. AbstractMesh.prototype.disableFacetData = function () {
  21355. if (this._facetDataEnabled) {
  21356. this._facetDataEnabled = false;
  21357. this._facetPositions = new Array();
  21358. this._facetNormals = new Array();
  21359. this._facetPartitioning = new Array();
  21360. this._facetParameters = null;
  21361. this._depthSortedIndices = new Uint32Array(0);
  21362. }
  21363. return this;
  21364. };
  21365. /**
  21366. * Updates the AbstractMesh indices array
  21367. * @param indices defines the data source
  21368. * @returns the current mesh
  21369. */
  21370. AbstractMesh.prototype.updateIndices = function (indices) {
  21371. return this;
  21372. };
  21373. /**
  21374. * Creates new normals data for the mesh
  21375. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21376. * @returns the current mesh
  21377. */
  21378. AbstractMesh.prototype.createNormals = function (updatable) {
  21379. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21380. var indices = this.getIndices();
  21381. var normals;
  21382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21383. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21384. }
  21385. else {
  21386. normals = [];
  21387. }
  21388. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21389. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21390. return this;
  21391. };
  21392. /**
  21393. * Align the mesh with a normal
  21394. * @param normal defines the normal to use
  21395. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21396. * @returns the current mesh
  21397. */
  21398. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21399. if (!upDirection) {
  21400. upDirection = BABYLON.Axis.Y;
  21401. }
  21402. var axisX = BABYLON.Tmp.Vector3[0];
  21403. var axisZ = BABYLON.Tmp.Vector3[1];
  21404. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21405. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21406. if (this.rotationQuaternion) {
  21407. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21408. }
  21409. else {
  21410. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21411. }
  21412. return this;
  21413. };
  21414. /** @hidden */
  21415. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21416. this._isOccluded = false;
  21417. };
  21418. /** No occlusion */
  21419. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21420. /** Occlusion set to optimisitic */
  21421. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21422. /** Occlusion set to strict */
  21423. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21424. /** Use an accurante occlusion algorithm */
  21425. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21426. /** Use a conservative occlusion algorithm */
  21427. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21428. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21429. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21430. /** Culling strategy with bounding sphere only and then frustum culling */
  21431. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21432. return AbstractMesh;
  21433. }(BABYLON.TransformNode));
  21434. BABYLON.AbstractMesh = AbstractMesh;
  21435. })(BABYLON || (BABYLON = {}));
  21436. //# sourceMappingURL=babylon.abstractMesh.js.map
  21437. var BABYLON;
  21438. (function (BABYLON) {
  21439. /**
  21440. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21441. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21442. * 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.
  21443. */
  21444. var Light = /** @class */ (function (_super) {
  21445. __extends(Light, _super);
  21446. /**
  21447. * Creates a Light object in the scene.
  21448. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21449. * @param name The firendly name of the light
  21450. * @param scene The scene the light belongs too
  21451. */
  21452. function Light(name, scene) {
  21453. var _this = _super.call(this, name, scene) || this;
  21454. /**
  21455. * Diffuse gives the basic color to an object.
  21456. */
  21457. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21458. /**
  21459. * Specular produces a highlight color on an object.
  21460. * Note: This is note affecting PBR materials.
  21461. */
  21462. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21463. /**
  21464. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21465. * falling off base on range or angle.
  21466. * This can be set to any values in Light.FALLOFF_x.
  21467. *
  21468. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21469. * other types of materials.
  21470. */
  21471. _this.falloffType = Light.FALLOFF_DEFAULT;
  21472. /**
  21473. * Strength of the light.
  21474. * Note: By default it is define in the framework own unit.
  21475. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21476. */
  21477. _this.intensity = 1.0;
  21478. _this._range = Number.MAX_VALUE;
  21479. _this._inverseSquaredRange = 0;
  21480. /**
  21481. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21482. * of light.
  21483. */
  21484. _this._photometricScale = 1.0;
  21485. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21486. _this._radius = 0.00001;
  21487. /**
  21488. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21489. * exceeding the number allowed of the materials.
  21490. */
  21491. _this.renderPriority = 0;
  21492. _this._shadowEnabled = true;
  21493. _this._excludeWithLayerMask = 0;
  21494. _this._includeOnlyWithLayerMask = 0;
  21495. _this._lightmapMode = 0;
  21496. /**
  21497. * @hidden Internal use only.
  21498. */
  21499. _this._excludedMeshesIds = new Array();
  21500. /**
  21501. * @hidden Internal use only.
  21502. */
  21503. _this._includedOnlyMeshesIds = new Array();
  21504. _this.getScene().addLight(_this);
  21505. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21506. _this._buildUniformLayout();
  21507. _this.includedOnlyMeshes = new Array();
  21508. _this.excludedMeshes = new Array();
  21509. _this._resyncMeshes();
  21510. return _this;
  21511. }
  21512. Object.defineProperty(Light.prototype, "range", {
  21513. /**
  21514. * Defines how far from the source the light is impacting in scene units.
  21515. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21516. */
  21517. get: function () {
  21518. return this._range;
  21519. },
  21520. /**
  21521. * Defines how far from the source the light is impacting in scene units.
  21522. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21523. */
  21524. set: function (value) {
  21525. this._range = value;
  21526. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. Object.defineProperty(Light.prototype, "intensityMode", {
  21532. /**
  21533. * Gets the photometric scale used to interpret the intensity.
  21534. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21535. */
  21536. get: function () {
  21537. return this._intensityMode;
  21538. },
  21539. /**
  21540. * Sets the photometric scale used to interpret the intensity.
  21541. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21542. */
  21543. set: function (value) {
  21544. this._intensityMode = value;
  21545. this._computePhotometricScale();
  21546. },
  21547. enumerable: true,
  21548. configurable: true
  21549. });
  21550. ;
  21551. ;
  21552. Object.defineProperty(Light.prototype, "radius", {
  21553. /**
  21554. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21555. */
  21556. get: function () {
  21557. return this._radius;
  21558. },
  21559. /**
  21560. * sets the light radius used by PBR Materials to simulate soft area lights.
  21561. */
  21562. set: function (value) {
  21563. this._radius = value;
  21564. this._computePhotometricScale();
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. ;
  21570. ;
  21571. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21572. /**
  21573. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21574. * the current shadow generator.
  21575. */
  21576. get: function () {
  21577. return this._shadowEnabled;
  21578. },
  21579. /**
  21580. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21581. * the current shadow generator.
  21582. */
  21583. set: function (value) {
  21584. if (this._shadowEnabled === value) {
  21585. return;
  21586. }
  21587. this._shadowEnabled = value;
  21588. this._markMeshesAsLightDirty();
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21594. /**
  21595. * Gets the only meshes impacted by this light.
  21596. */
  21597. get: function () {
  21598. return this._includedOnlyMeshes;
  21599. },
  21600. /**
  21601. * Sets the only meshes impacted by this light.
  21602. */
  21603. set: function (value) {
  21604. this._includedOnlyMeshes = value;
  21605. this._hookArrayForIncludedOnly(value);
  21606. },
  21607. enumerable: true,
  21608. configurable: true
  21609. });
  21610. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21611. /**
  21612. * Gets the meshes not impacted by this light.
  21613. */
  21614. get: function () {
  21615. return this._excludedMeshes;
  21616. },
  21617. /**
  21618. * Sets the meshes not impacted by this light.
  21619. */
  21620. set: function (value) {
  21621. this._excludedMeshes = value;
  21622. this._hookArrayForExcluded(value);
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21628. /**
  21629. * Gets the layer id use to find what meshes are not impacted by the light.
  21630. * Inactive if 0
  21631. */
  21632. get: function () {
  21633. return this._excludeWithLayerMask;
  21634. },
  21635. /**
  21636. * Sets the layer id use to find what meshes are not impacted by the light.
  21637. * Inactive if 0
  21638. */
  21639. set: function (value) {
  21640. this._excludeWithLayerMask = value;
  21641. this._resyncMeshes();
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21647. /**
  21648. * Gets the layer id use to find what meshes are impacted by the light.
  21649. * Inactive if 0
  21650. */
  21651. get: function () {
  21652. return this._includeOnlyWithLayerMask;
  21653. },
  21654. /**
  21655. * Sets the layer id use to find what meshes are impacted by the light.
  21656. * Inactive if 0
  21657. */
  21658. set: function (value) {
  21659. this._includeOnlyWithLayerMask = value;
  21660. this._resyncMeshes();
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Light.prototype, "lightmapMode", {
  21666. /**
  21667. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21668. */
  21669. get: function () {
  21670. return this._lightmapMode;
  21671. },
  21672. /**
  21673. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21674. */
  21675. set: function (value) {
  21676. if (this._lightmapMode === value) {
  21677. return;
  21678. }
  21679. this._lightmapMode = value;
  21680. this._markMeshesAsLightDirty();
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. /**
  21686. * Returns the string "Light".
  21687. * @returns the class name
  21688. */
  21689. Light.prototype.getClassName = function () {
  21690. return "Light";
  21691. };
  21692. /**
  21693. * Converts the light information to a readable string for debug purpose.
  21694. * @param fullDetails Supports for multiple levels of logging within scene loading
  21695. * @returns the human readable light info
  21696. */
  21697. Light.prototype.toString = function (fullDetails) {
  21698. var ret = "Name: " + this.name;
  21699. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21700. if (this.animations) {
  21701. for (var i = 0; i < this.animations.length; i++) {
  21702. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21703. }
  21704. }
  21705. if (fullDetails) {
  21706. }
  21707. return ret;
  21708. };
  21709. /**
  21710. * Set the enabled state of this node.
  21711. * @param value - the new enabled state
  21712. */
  21713. Light.prototype.setEnabled = function (value) {
  21714. _super.prototype.setEnabled.call(this, value);
  21715. this._resyncMeshes();
  21716. };
  21717. /**
  21718. * Returns the Light associated shadow generator if any.
  21719. * @return the associated shadow generator.
  21720. */
  21721. Light.prototype.getShadowGenerator = function () {
  21722. return this._shadowGenerator;
  21723. };
  21724. /**
  21725. * Returns a Vector3, the absolute light position in the World.
  21726. * @returns the world space position of the light
  21727. */
  21728. Light.prototype.getAbsolutePosition = function () {
  21729. return BABYLON.Vector3.Zero();
  21730. };
  21731. /**
  21732. * Specifies if the light will affect the passed mesh.
  21733. * @param mesh The mesh to test against the light
  21734. * @return true the mesh is affected otherwise, false.
  21735. */
  21736. Light.prototype.canAffectMesh = function (mesh) {
  21737. if (!mesh) {
  21738. return true;
  21739. }
  21740. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21741. return false;
  21742. }
  21743. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21744. return false;
  21745. }
  21746. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21747. return false;
  21748. }
  21749. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21750. return false;
  21751. }
  21752. return true;
  21753. };
  21754. /**
  21755. * Computes and Returns the light World matrix.
  21756. * @returns the world matrix
  21757. */
  21758. Light.prototype.getWorldMatrix = function () {
  21759. this._currentRenderId = this.getScene().getRenderId();
  21760. this._childRenderId = this._currentRenderId;
  21761. var worldMatrix = this._getWorldMatrix();
  21762. if (this.parent && this.parent.getWorldMatrix) {
  21763. if (!this._parentedWorldMatrix) {
  21764. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21765. }
  21766. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21767. this._markSyncedWithParent();
  21768. return this._parentedWorldMatrix;
  21769. }
  21770. return worldMatrix;
  21771. };
  21772. /**
  21773. * Sort function to order lights for rendering.
  21774. * @param a First Light object to compare to second.
  21775. * @param b Second Light object to compare first.
  21776. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21777. */
  21778. Light.CompareLightsPriority = function (a, b) {
  21779. //shadow-casting lights have priority over non-shadow-casting lights
  21780. //the renderPrioirty is a secondary sort criterion
  21781. if (a.shadowEnabled !== b.shadowEnabled) {
  21782. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21783. }
  21784. return b.renderPriority - a.renderPriority;
  21785. };
  21786. /**
  21787. * Releases resources associated with this node.
  21788. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21789. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21790. */
  21791. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21792. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21793. if (this._shadowGenerator) {
  21794. this._shadowGenerator.dispose();
  21795. this._shadowGenerator = null;
  21796. }
  21797. // Animations
  21798. this.getScene().stopAnimation(this);
  21799. // Remove from meshes
  21800. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21801. var mesh = _a[_i];
  21802. mesh._removeLightSource(this);
  21803. }
  21804. this._uniformBuffer.dispose();
  21805. // Remove from scene
  21806. this.getScene().removeLight(this);
  21807. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21808. };
  21809. /**
  21810. * Returns the light type ID (integer).
  21811. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21812. */
  21813. Light.prototype.getTypeID = function () {
  21814. return 0;
  21815. };
  21816. /**
  21817. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21818. * @returns the scaled intensity in intensity mode unit
  21819. */
  21820. Light.prototype.getScaledIntensity = function () {
  21821. return this._photometricScale * this.intensity;
  21822. };
  21823. /**
  21824. * Returns a new Light object, named "name", from the current one.
  21825. * @param name The name of the cloned light
  21826. * @returns the new created light
  21827. */
  21828. Light.prototype.clone = function (name) {
  21829. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21830. if (!constructor) {
  21831. return null;
  21832. }
  21833. return BABYLON.SerializationHelper.Clone(constructor, this);
  21834. };
  21835. /**
  21836. * Serializes the current light into a Serialization object.
  21837. * @returns the serialized object.
  21838. */
  21839. Light.prototype.serialize = function () {
  21840. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21841. // Type
  21842. serializationObject.type = this.getTypeID();
  21843. // Parent
  21844. if (this.parent) {
  21845. serializationObject.parentId = this.parent.id;
  21846. }
  21847. // Inclusion / exclusions
  21848. if (this.excludedMeshes.length > 0) {
  21849. serializationObject.excludedMeshesIds = [];
  21850. this.excludedMeshes.forEach(function (mesh) {
  21851. serializationObject.excludedMeshesIds.push(mesh.id);
  21852. });
  21853. }
  21854. if (this.includedOnlyMeshes.length > 0) {
  21855. serializationObject.includedOnlyMeshesIds = [];
  21856. this.includedOnlyMeshes.forEach(function (mesh) {
  21857. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21858. });
  21859. }
  21860. // Animations
  21861. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21862. serializationObject.ranges = this.serializeAnimationRanges();
  21863. return serializationObject;
  21864. };
  21865. /**
  21866. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21867. * This new light is named "name" and added to the passed scene.
  21868. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21869. * @param name The friendly name of the light
  21870. * @param scene The scene the new light will belong to
  21871. * @returns the constructor function
  21872. */
  21873. Light.GetConstructorFromName = function (type, name, scene) {
  21874. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21875. if (constructorFunc) {
  21876. return constructorFunc;
  21877. }
  21878. // Default to no light for none present once.
  21879. return null;
  21880. };
  21881. /**
  21882. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21883. * @param parsedLight The JSON representation of the light
  21884. * @param scene The scene to create the parsed light in
  21885. * @returns the created light after parsing
  21886. */
  21887. Light.Parse = function (parsedLight, scene) {
  21888. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21889. if (!constructor) {
  21890. return null;
  21891. }
  21892. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21893. // Inclusion / exclusions
  21894. if (parsedLight.excludedMeshesIds) {
  21895. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21896. }
  21897. if (parsedLight.includedOnlyMeshesIds) {
  21898. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21899. }
  21900. // Parent
  21901. if (parsedLight.parentId) {
  21902. light._waitingParentId = parsedLight.parentId;
  21903. }
  21904. // Animations
  21905. if (parsedLight.animations) {
  21906. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21907. var parsedAnimation = parsedLight.animations[animationIndex];
  21908. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21909. }
  21910. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21911. }
  21912. if (parsedLight.autoAnimate) {
  21913. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21914. }
  21915. return light;
  21916. };
  21917. Light.prototype._hookArrayForExcluded = function (array) {
  21918. var _this = this;
  21919. var oldPush = array.push;
  21920. array.push = function () {
  21921. var items = [];
  21922. for (var _i = 0; _i < arguments.length; _i++) {
  21923. items[_i] = arguments[_i];
  21924. }
  21925. var result = oldPush.apply(array, items);
  21926. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21927. var item = items_1[_a];
  21928. item._resyncLighSource(_this);
  21929. }
  21930. return result;
  21931. };
  21932. var oldSplice = array.splice;
  21933. array.splice = function (index, deleteCount) {
  21934. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21935. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21936. var item = deleted_1[_i];
  21937. item._resyncLighSource(_this);
  21938. }
  21939. return deleted;
  21940. };
  21941. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21942. var item = array_1[_i];
  21943. item._resyncLighSource(this);
  21944. }
  21945. };
  21946. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21947. var _this = this;
  21948. var oldPush = array.push;
  21949. array.push = function () {
  21950. var items = [];
  21951. for (var _i = 0; _i < arguments.length; _i++) {
  21952. items[_i] = arguments[_i];
  21953. }
  21954. var result = oldPush.apply(array, items);
  21955. _this._resyncMeshes();
  21956. return result;
  21957. };
  21958. var oldSplice = array.splice;
  21959. array.splice = function (index, deleteCount) {
  21960. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21961. _this._resyncMeshes();
  21962. return deleted;
  21963. };
  21964. this._resyncMeshes();
  21965. };
  21966. Light.prototype._resyncMeshes = function () {
  21967. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21968. var mesh = _a[_i];
  21969. mesh._resyncLighSource(this);
  21970. }
  21971. };
  21972. /**
  21973. * Forces the meshes to update their light related information in their rendering used effects
  21974. * @hidden Internal Use Only
  21975. */
  21976. Light.prototype._markMeshesAsLightDirty = function () {
  21977. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21978. var mesh = _a[_i];
  21979. if (mesh._lightSources.indexOf(this) !== -1) {
  21980. mesh._markSubMeshesAsLightDirty();
  21981. }
  21982. }
  21983. };
  21984. /**
  21985. * Recomputes the cached photometric scale if needed.
  21986. */
  21987. Light.prototype._computePhotometricScale = function () {
  21988. this._photometricScale = this._getPhotometricScale();
  21989. this.getScene().resetCachedMaterial();
  21990. };
  21991. /**
  21992. * Returns the Photometric Scale according to the light type and intensity mode.
  21993. */
  21994. Light.prototype._getPhotometricScale = function () {
  21995. var photometricScale = 0.0;
  21996. var lightTypeID = this.getTypeID();
  21997. //get photometric mode
  21998. var photometricMode = this.intensityMode;
  21999. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22000. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22001. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22002. }
  22003. else {
  22004. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22005. }
  22006. }
  22007. //compute photometric scale
  22008. switch (lightTypeID) {
  22009. case Light.LIGHTTYPEID_POINTLIGHT:
  22010. case Light.LIGHTTYPEID_SPOTLIGHT:
  22011. switch (photometricMode) {
  22012. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22013. photometricScale = 1.0 / (4.0 * Math.PI);
  22014. break;
  22015. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22016. photometricScale = 1.0;
  22017. break;
  22018. case Light.INTENSITYMODE_LUMINANCE:
  22019. photometricScale = this.radius * this.radius;
  22020. break;
  22021. }
  22022. break;
  22023. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22024. switch (photometricMode) {
  22025. case Light.INTENSITYMODE_ILLUMINANCE:
  22026. photometricScale = 1.0;
  22027. break;
  22028. case Light.INTENSITYMODE_LUMINANCE:
  22029. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22030. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22031. var apexAngleRadians = this.radius;
  22032. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22033. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22034. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22035. photometricScale = solidAngle;
  22036. break;
  22037. }
  22038. break;
  22039. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22040. // No fall off in hemisperic light.
  22041. photometricScale = 1.0;
  22042. break;
  22043. }
  22044. return photometricScale;
  22045. };
  22046. /**
  22047. * Reorder the light in the scene according to their defined priority.
  22048. * @hidden Internal Use Only
  22049. */
  22050. Light.prototype._reorderLightsInScene = function () {
  22051. var scene = this.getScene();
  22052. if (this._renderPriority != 0) {
  22053. scene.requireLightSorting = true;
  22054. }
  22055. this.getScene().sortLightsByPriority();
  22056. };
  22057. /**
  22058. * Falloff Default: light is falling off following the material specification:
  22059. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22060. */
  22061. Light.FALLOFF_DEFAULT = 0;
  22062. /**
  22063. * Falloff Physical: light is falling off following the inverse squared distance law.
  22064. */
  22065. Light.FALLOFF_PHYSICAL = 1;
  22066. /**
  22067. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22068. * to enhance interoperability with other engines.
  22069. */
  22070. Light.FALLOFF_GLTF = 2;
  22071. /**
  22072. * Falloff Standard: light is falling off like in the standard material
  22073. * to enhance interoperability with other materials.
  22074. */
  22075. Light.FALLOFF_STANDARD = 3;
  22076. //lightmapMode Consts
  22077. /**
  22078. * If every light affecting the material is in this lightmapMode,
  22079. * material.lightmapTexture adds or multiplies
  22080. * (depends on material.useLightmapAsShadowmap)
  22081. * after every other light calculations.
  22082. */
  22083. Light.LIGHTMAP_DEFAULT = 0;
  22084. /**
  22085. * material.lightmapTexture as only diffuse lighting from this light
  22086. * adds only specular lighting from this light
  22087. * adds dynamic shadows
  22088. */
  22089. Light.LIGHTMAP_SPECULAR = 1;
  22090. /**
  22091. * material.lightmapTexture as only lighting
  22092. * no light calculation from this light
  22093. * only adds dynamic shadows from this light
  22094. */
  22095. Light.LIGHTMAP_SHADOWSONLY = 2;
  22096. // Intensity Mode Consts
  22097. /**
  22098. * Each light type uses the default quantity according to its type:
  22099. * point/spot lights use luminous intensity
  22100. * directional lights use illuminance
  22101. */
  22102. Light.INTENSITYMODE_AUTOMATIC = 0;
  22103. /**
  22104. * lumen (lm)
  22105. */
  22106. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22107. /**
  22108. * candela (lm/sr)
  22109. */
  22110. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22111. /**
  22112. * lux (lm/m^2)
  22113. */
  22114. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22115. /**
  22116. * nit (cd/m^2)
  22117. */
  22118. Light.INTENSITYMODE_LUMINANCE = 4;
  22119. // Light types ids const.
  22120. /**
  22121. * Light type const id of the point light.
  22122. */
  22123. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22124. /**
  22125. * Light type const id of the directional light.
  22126. */
  22127. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22128. /**
  22129. * Light type const id of the spot light.
  22130. */
  22131. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22132. /**
  22133. * Light type const id of the hemispheric light.
  22134. */
  22135. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22136. __decorate([
  22137. BABYLON.serializeAsColor3()
  22138. ], Light.prototype, "diffuse", void 0);
  22139. __decorate([
  22140. BABYLON.serializeAsColor3()
  22141. ], Light.prototype, "specular", void 0);
  22142. __decorate([
  22143. BABYLON.serialize()
  22144. ], Light.prototype, "falloffType", void 0);
  22145. __decorate([
  22146. BABYLON.serialize()
  22147. ], Light.prototype, "intensity", void 0);
  22148. __decorate([
  22149. BABYLON.serialize()
  22150. ], Light.prototype, "range", null);
  22151. __decorate([
  22152. BABYLON.serialize()
  22153. ], Light.prototype, "intensityMode", null);
  22154. __decorate([
  22155. BABYLON.serialize()
  22156. ], Light.prototype, "radius", null);
  22157. __decorate([
  22158. BABYLON.serialize()
  22159. ], Light.prototype, "_renderPriority", void 0);
  22160. __decorate([
  22161. BABYLON.expandToProperty("_reorderLightsInScene")
  22162. ], Light.prototype, "renderPriority", void 0);
  22163. __decorate([
  22164. BABYLON.serialize("shadowEnabled")
  22165. ], Light.prototype, "_shadowEnabled", void 0);
  22166. __decorate([
  22167. BABYLON.serialize("excludeWithLayerMask")
  22168. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22169. __decorate([
  22170. BABYLON.serialize("includeOnlyWithLayerMask")
  22171. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22172. __decorate([
  22173. BABYLON.serialize("lightmapMode")
  22174. ], Light.prototype, "_lightmapMode", void 0);
  22175. return Light;
  22176. }(BABYLON.Node));
  22177. BABYLON.Light = Light;
  22178. })(BABYLON || (BABYLON = {}));
  22179. //# sourceMappingURL=babylon.light.js.map
  22180. var BABYLON;
  22181. (function (BABYLON) {
  22182. var Camera = /** @class */ (function (_super) {
  22183. __extends(Camera, _super);
  22184. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22185. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22186. var _this = _super.call(this, name, scene) || this;
  22187. /**
  22188. * The vector the camera should consider as up.
  22189. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22190. */
  22191. _this.upVector = BABYLON.Vector3.Up();
  22192. _this.orthoLeft = null;
  22193. _this.orthoRight = null;
  22194. _this.orthoBottom = null;
  22195. _this.orthoTop = null;
  22196. /**
  22197. * FOV is set in Radians. (default is 0.8)
  22198. */
  22199. _this.fov = 0.8;
  22200. _this.minZ = 1;
  22201. _this.maxZ = 10000.0;
  22202. _this.inertia = 0.9;
  22203. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22204. _this.isIntermediate = false;
  22205. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22206. /**
  22207. * Restricts the camera to viewing objects with the same layerMask.
  22208. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22209. */
  22210. _this.layerMask = 0x0FFFFFFF;
  22211. /**
  22212. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22213. */
  22214. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22215. // Camera rig members
  22216. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22217. /** @hidden */
  22218. _this._rigCameras = new Array();
  22219. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22220. /** @hidden */
  22221. _this._skipRendering = false;
  22222. _this.customRenderTargets = new Array();
  22223. // Observables
  22224. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22225. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22226. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22227. _this.onRestoreStateObservable = new BABYLON.Observable();
  22228. // Cache
  22229. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22230. _this._projectionMatrix = new BABYLON.Matrix();
  22231. _this._doNotComputeProjectionMatrix = false;
  22232. _this._worldMatrix = BABYLON.Matrix.Identity();
  22233. _this._postProcesses = new Array();
  22234. _this._transformMatrix = BABYLON.Matrix.Zero();
  22235. _this._activeMeshes = new BABYLON.SmartArray(256);
  22236. _this._globalPosition = BABYLON.Vector3.Zero();
  22237. _this._refreshFrustumPlanes = true;
  22238. _this.getScene().addCamera(_this);
  22239. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22240. _this.getScene().activeCamera = _this;
  22241. }
  22242. _this.position = position;
  22243. return _this;
  22244. }
  22245. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22246. get: function () {
  22247. return Camera._PERSPECTIVE_CAMERA;
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22253. get: function () {
  22254. return Camera._ORTHOGRAPHIC_CAMERA;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22260. /**
  22261. * This is the default FOV mode for perspective cameras.
  22262. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22263. *
  22264. */
  22265. get: function () {
  22266. return Camera._FOVMODE_VERTICAL_FIXED;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22272. /**
  22273. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22274. *
  22275. */
  22276. get: function () {
  22277. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22278. },
  22279. enumerable: true,
  22280. configurable: true
  22281. });
  22282. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22283. get: function () {
  22284. return Camera._RIG_MODE_NONE;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22290. get: function () {
  22291. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22297. get: function () {
  22298. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22304. get: function () {
  22305. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22306. },
  22307. enumerable: true,
  22308. configurable: true
  22309. });
  22310. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22311. get: function () {
  22312. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22313. },
  22314. enumerable: true,
  22315. configurable: true
  22316. });
  22317. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22318. get: function () {
  22319. return Camera._RIG_MODE_VR;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22325. get: function () {
  22326. return Camera._RIG_MODE_WEBVR;
  22327. },
  22328. enumerable: true,
  22329. configurable: true
  22330. });
  22331. /**
  22332. * Store current camera state (fov, position, etc..)
  22333. */
  22334. Camera.prototype.storeState = function () {
  22335. this._stateStored = true;
  22336. this._storedFov = this.fov;
  22337. return this;
  22338. };
  22339. /**
  22340. * Restores the camera state values if it has been stored. You must call storeState() first
  22341. */
  22342. Camera.prototype._restoreStateValues = function () {
  22343. if (!this._stateStored) {
  22344. return false;
  22345. }
  22346. this.fov = this._storedFov;
  22347. return true;
  22348. };
  22349. /**
  22350. * Restored camera state. You must call storeState() first
  22351. */
  22352. Camera.prototype.restoreState = function () {
  22353. if (this._restoreStateValues()) {
  22354. this.onRestoreStateObservable.notifyObservers(this);
  22355. return true;
  22356. }
  22357. return false;
  22358. };
  22359. Camera.prototype.getClassName = function () {
  22360. return "Camera";
  22361. };
  22362. /**
  22363. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22364. */
  22365. Camera.prototype.toString = function (fullDetails) {
  22366. var ret = "Name: " + this.name;
  22367. ret += ", type: " + this.getClassName();
  22368. if (this.animations) {
  22369. for (var i = 0; i < this.animations.length; i++) {
  22370. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22371. }
  22372. }
  22373. if (fullDetails) {
  22374. }
  22375. return ret;
  22376. };
  22377. Object.defineProperty(Camera.prototype, "globalPosition", {
  22378. get: function () {
  22379. return this._globalPosition;
  22380. },
  22381. enumerable: true,
  22382. configurable: true
  22383. });
  22384. Camera.prototype.getActiveMeshes = function () {
  22385. return this._activeMeshes;
  22386. };
  22387. Camera.prototype.isActiveMesh = function (mesh) {
  22388. return (this._activeMeshes.indexOf(mesh) !== -1);
  22389. };
  22390. /**
  22391. * Is this camera ready to be used/rendered
  22392. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22393. * @return true if the camera is ready
  22394. */
  22395. Camera.prototype.isReady = function (completeCheck) {
  22396. if (completeCheck === void 0) { completeCheck = false; }
  22397. if (completeCheck) {
  22398. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22399. var pp = _a[_i];
  22400. if (pp && !pp.isReady()) {
  22401. return false;
  22402. }
  22403. }
  22404. }
  22405. return _super.prototype.isReady.call(this, completeCheck);
  22406. };
  22407. //Cache
  22408. /** @hidden */
  22409. Camera.prototype._initCache = function () {
  22410. _super.prototype._initCache.call(this);
  22411. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22412. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22413. this._cache.mode = undefined;
  22414. this._cache.minZ = undefined;
  22415. this._cache.maxZ = undefined;
  22416. this._cache.fov = undefined;
  22417. this._cache.fovMode = undefined;
  22418. this._cache.aspectRatio = undefined;
  22419. this._cache.orthoLeft = undefined;
  22420. this._cache.orthoRight = undefined;
  22421. this._cache.orthoBottom = undefined;
  22422. this._cache.orthoTop = undefined;
  22423. this._cache.renderWidth = undefined;
  22424. this._cache.renderHeight = undefined;
  22425. };
  22426. /** @hidden */
  22427. Camera.prototype._updateCache = function (ignoreParentClass) {
  22428. if (!ignoreParentClass) {
  22429. _super.prototype._updateCache.call(this);
  22430. }
  22431. this._cache.position.copyFrom(this.position);
  22432. this._cache.upVector.copyFrom(this.upVector);
  22433. };
  22434. // Synchronized
  22435. /** @hidden */
  22436. Camera.prototype._isSynchronized = function () {
  22437. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22438. };
  22439. /** @hidden */
  22440. Camera.prototype._isSynchronizedViewMatrix = function () {
  22441. if (!_super.prototype._isSynchronized.call(this))
  22442. return false;
  22443. return this._cache.position.equals(this.position)
  22444. && this._cache.upVector.equals(this.upVector)
  22445. && this.isSynchronizedWithParent();
  22446. };
  22447. /** @hidden */
  22448. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22449. var check = this._cache.mode === this.mode
  22450. && this._cache.minZ === this.minZ
  22451. && this._cache.maxZ === this.maxZ;
  22452. if (!check) {
  22453. return false;
  22454. }
  22455. var engine = this.getEngine();
  22456. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22457. check = this._cache.fov === this.fov
  22458. && this._cache.fovMode === this.fovMode
  22459. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22460. }
  22461. else {
  22462. check = this._cache.orthoLeft === this.orthoLeft
  22463. && this._cache.orthoRight === this.orthoRight
  22464. && this._cache.orthoBottom === this.orthoBottom
  22465. && this._cache.orthoTop === this.orthoTop
  22466. && this._cache.renderWidth === engine.getRenderWidth()
  22467. && this._cache.renderHeight === engine.getRenderHeight();
  22468. }
  22469. return check;
  22470. };
  22471. // Controls
  22472. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22473. };
  22474. Camera.prototype.detachControl = function (element) {
  22475. };
  22476. Camera.prototype.update = function () {
  22477. this._checkInputs();
  22478. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22479. this._updateRigCameras();
  22480. }
  22481. };
  22482. /** @hidden */
  22483. Camera.prototype._checkInputs = function () {
  22484. this.onAfterCheckInputsObservable.notifyObservers(this);
  22485. };
  22486. Object.defineProperty(Camera.prototype, "rigCameras", {
  22487. get: function () {
  22488. return this._rigCameras;
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22494. get: function () {
  22495. return this._rigPostProcess;
  22496. },
  22497. enumerable: true,
  22498. configurable: true
  22499. });
  22500. /**
  22501. * Internal, gets the first post proces.
  22502. * @returns the first post process to be run on this camera.
  22503. */
  22504. Camera.prototype._getFirstPostProcess = function () {
  22505. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22506. if (this._postProcesses[ppIndex] !== null) {
  22507. return this._postProcesses[ppIndex];
  22508. }
  22509. }
  22510. return null;
  22511. };
  22512. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22513. // invalidate framebuffer
  22514. var firstPostProcess = this._getFirstPostProcess();
  22515. if (firstPostProcess) {
  22516. firstPostProcess.markTextureDirty();
  22517. }
  22518. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22519. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22520. var cam = this._rigCameras[i];
  22521. var rigPostProcess = cam._rigPostProcess;
  22522. // for VR rig, there does not have to be a post process
  22523. if (rigPostProcess) {
  22524. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22525. if (isPass) {
  22526. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22527. cam.isIntermediate = this._postProcesses.length === 0;
  22528. }
  22529. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22530. rigPostProcess.markTextureDirty();
  22531. }
  22532. else {
  22533. cam._postProcesses = this._postProcesses.slice(0);
  22534. }
  22535. }
  22536. };
  22537. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22538. if (insertAt === void 0) { insertAt = null; }
  22539. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22540. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22541. return 0;
  22542. }
  22543. if (insertAt == null || insertAt < 0) {
  22544. this._postProcesses.push(postProcess);
  22545. }
  22546. else if (this._postProcesses[insertAt] === null) {
  22547. this._postProcesses[insertAt] = postProcess;
  22548. }
  22549. else {
  22550. this._postProcesses.splice(insertAt, 0, postProcess);
  22551. }
  22552. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22553. return this._postProcesses.indexOf(postProcess);
  22554. };
  22555. Camera.prototype.detachPostProcess = function (postProcess) {
  22556. var idx = this._postProcesses.indexOf(postProcess);
  22557. if (idx !== -1) {
  22558. this._postProcesses[idx] = null;
  22559. }
  22560. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22561. };
  22562. Camera.prototype.getWorldMatrix = function () {
  22563. if (this._isSynchronizedViewMatrix()) {
  22564. return this._worldMatrix;
  22565. }
  22566. // Getting the the view matrix will also compute the world matrix.
  22567. this.getViewMatrix();
  22568. return this._worldMatrix;
  22569. };
  22570. /** @hidden */
  22571. Camera.prototype._getViewMatrix = function () {
  22572. return BABYLON.Matrix.Identity();
  22573. };
  22574. Camera.prototype.getViewMatrix = function (force) {
  22575. if (!force && this._isSynchronizedViewMatrix()) {
  22576. return this._computedViewMatrix;
  22577. }
  22578. this.updateCache();
  22579. this._computedViewMatrix = this._getViewMatrix();
  22580. this._currentRenderId = this.getScene().getRenderId();
  22581. this._childRenderId = this._currentRenderId;
  22582. this._refreshFrustumPlanes = true;
  22583. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22584. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22585. }
  22586. this.onViewMatrixChangedObservable.notifyObservers(this);
  22587. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22588. return this._computedViewMatrix;
  22589. };
  22590. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22591. this._doNotComputeProjectionMatrix = true;
  22592. if (projection !== undefined) {
  22593. this._projectionMatrix = projection;
  22594. }
  22595. };
  22596. ;
  22597. Camera.prototype.unfreezeProjectionMatrix = function () {
  22598. this._doNotComputeProjectionMatrix = false;
  22599. };
  22600. ;
  22601. Camera.prototype.getProjectionMatrix = function (force) {
  22602. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22603. return this._projectionMatrix;
  22604. }
  22605. // Cache
  22606. this._cache.mode = this.mode;
  22607. this._cache.minZ = this.minZ;
  22608. this._cache.maxZ = this.maxZ;
  22609. // Matrix
  22610. this._refreshFrustumPlanes = true;
  22611. var engine = this.getEngine();
  22612. var scene = this.getScene();
  22613. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22614. this._cache.fov = this.fov;
  22615. this._cache.fovMode = this.fovMode;
  22616. this._cache.aspectRatio = engine.getAspectRatio(this);
  22617. if (this.minZ <= 0) {
  22618. this.minZ = 0.1;
  22619. }
  22620. if (scene.useRightHandedSystem) {
  22621. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22622. }
  22623. else {
  22624. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22625. }
  22626. }
  22627. else {
  22628. var halfWidth = engine.getRenderWidth() / 2.0;
  22629. var halfHeight = engine.getRenderHeight() / 2.0;
  22630. if (scene.useRightHandedSystem) {
  22631. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22632. }
  22633. else {
  22634. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22635. }
  22636. this._cache.orthoLeft = this.orthoLeft;
  22637. this._cache.orthoRight = this.orthoRight;
  22638. this._cache.orthoBottom = this.orthoBottom;
  22639. this._cache.orthoTop = this.orthoTop;
  22640. this._cache.renderWidth = engine.getRenderWidth();
  22641. this._cache.renderHeight = engine.getRenderHeight();
  22642. }
  22643. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22644. return this._projectionMatrix;
  22645. };
  22646. /**
  22647. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22648. * @returns a Matrix
  22649. */
  22650. Camera.prototype.getTransformationMatrix = function () {
  22651. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22652. return this._transformMatrix;
  22653. };
  22654. Camera.prototype.updateFrustumPlanes = function () {
  22655. if (!this._refreshFrustumPlanes) {
  22656. return;
  22657. }
  22658. this.getTransformationMatrix();
  22659. if (!this._frustumPlanes) {
  22660. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22661. }
  22662. else {
  22663. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22664. }
  22665. this._refreshFrustumPlanes = false;
  22666. };
  22667. Camera.prototype.isInFrustum = function (target) {
  22668. this.updateFrustumPlanes();
  22669. return target.isInFrustum(this._frustumPlanes);
  22670. };
  22671. Camera.prototype.isCompletelyInFrustum = function (target) {
  22672. this.updateFrustumPlanes();
  22673. return target.isCompletelyInFrustum(this._frustumPlanes);
  22674. };
  22675. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22676. if (length === void 0) { length = 100; }
  22677. if (!transform) {
  22678. transform = this.getWorldMatrix();
  22679. }
  22680. if (!origin) {
  22681. origin = this.position;
  22682. }
  22683. var forward = new BABYLON.Vector3(0, 0, 1);
  22684. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22685. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22686. return new BABYLON.Ray(origin, direction, length);
  22687. };
  22688. /**
  22689. * Releases resources associated with this node.
  22690. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22691. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22692. */
  22693. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22694. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22695. // Observables
  22696. this.onViewMatrixChangedObservable.clear();
  22697. this.onProjectionMatrixChangedObservable.clear();
  22698. this.onAfterCheckInputsObservable.clear();
  22699. this.onRestoreStateObservable.clear();
  22700. // Inputs
  22701. if (this.inputs) {
  22702. this.inputs.clear();
  22703. }
  22704. // Animations
  22705. this.getScene().stopAnimation(this);
  22706. // Remove from scene
  22707. this.getScene().removeCamera(this);
  22708. while (this._rigCameras.length > 0) {
  22709. var camera = this._rigCameras.pop();
  22710. if (camera) {
  22711. camera.dispose();
  22712. }
  22713. }
  22714. // Postprocesses
  22715. if (this._rigPostProcess) {
  22716. this._rigPostProcess.dispose(this);
  22717. this._rigPostProcess = null;
  22718. this._postProcesses = [];
  22719. }
  22720. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22721. this._rigPostProcess = null;
  22722. this._postProcesses = [];
  22723. }
  22724. else {
  22725. var i = this._postProcesses.length;
  22726. while (--i >= 0) {
  22727. var postProcess = this._postProcesses[i];
  22728. if (postProcess) {
  22729. postProcess.dispose(this);
  22730. }
  22731. }
  22732. }
  22733. // Render targets
  22734. var i = this.customRenderTargets.length;
  22735. while (--i >= 0) {
  22736. this.customRenderTargets[i].dispose();
  22737. }
  22738. this.customRenderTargets = [];
  22739. // Active Meshes
  22740. this._activeMeshes.dispose();
  22741. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22742. };
  22743. Object.defineProperty(Camera.prototype, "leftCamera", {
  22744. // ---- Camera rigs section ----
  22745. get: function () {
  22746. if (this._rigCameras.length < 1) {
  22747. return null;
  22748. }
  22749. return this._rigCameras[0];
  22750. },
  22751. enumerable: true,
  22752. configurable: true
  22753. });
  22754. Object.defineProperty(Camera.prototype, "rightCamera", {
  22755. get: function () {
  22756. if (this._rigCameras.length < 2) {
  22757. return null;
  22758. }
  22759. return this._rigCameras[1];
  22760. },
  22761. enumerable: true,
  22762. configurable: true
  22763. });
  22764. Camera.prototype.getLeftTarget = function () {
  22765. if (this._rigCameras.length < 1) {
  22766. return null;
  22767. }
  22768. return this._rigCameras[0].getTarget();
  22769. };
  22770. Camera.prototype.getRightTarget = function () {
  22771. if (this._rigCameras.length < 2) {
  22772. return null;
  22773. }
  22774. return this._rigCameras[1].getTarget();
  22775. };
  22776. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22777. if (this.cameraRigMode === mode) {
  22778. return;
  22779. }
  22780. while (this._rigCameras.length > 0) {
  22781. var camera = this._rigCameras.pop();
  22782. if (camera) {
  22783. camera.dispose();
  22784. }
  22785. }
  22786. this.cameraRigMode = mode;
  22787. this._cameraRigParams = {};
  22788. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22789. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22790. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22791. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22792. // create the rig cameras, unless none
  22793. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22794. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22795. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22796. if (leftCamera && rightCamera) {
  22797. this._rigCameras.push(leftCamera);
  22798. this._rigCameras.push(rightCamera);
  22799. }
  22800. }
  22801. switch (this.cameraRigMode) {
  22802. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22803. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22804. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22805. break;
  22806. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22807. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22808. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22809. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22810. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22811. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22812. break;
  22813. case Camera.RIG_MODE_VR:
  22814. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22815. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22816. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22817. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22818. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22819. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22820. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22821. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22822. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22823. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22824. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22825. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22826. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22827. if (metrics.compensateDistortion) {
  22828. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22829. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22830. }
  22831. break;
  22832. case Camera.RIG_MODE_WEBVR:
  22833. if (rigParams.vrDisplay) {
  22834. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22835. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22836. //Left eye
  22837. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22838. this._rigCameras[0].setCameraRigParameter("left", true);
  22839. //leaving this for future reference
  22840. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22841. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22842. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22843. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22844. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22845. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22846. this._rigCameras[0].parent = this;
  22847. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22848. //Right eye
  22849. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22850. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22851. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22852. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22853. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22854. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22855. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22856. this._rigCameras[1].parent = this;
  22857. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22858. if (Camera.UseAlternateWebVRRendering) {
  22859. this._rigCameras[1]._skipRendering = true;
  22860. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22861. }
  22862. }
  22863. break;
  22864. }
  22865. this._cascadePostProcessesToRigCams();
  22866. this.update();
  22867. };
  22868. Camera.prototype._getVRProjectionMatrix = function () {
  22869. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22870. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22871. return this._projectionMatrix;
  22872. };
  22873. Camera.prototype._updateCameraRotationMatrix = function () {
  22874. //Here for WebVR
  22875. };
  22876. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22877. //Here for WebVR
  22878. };
  22879. /**
  22880. * This function MUST be overwritten by the different WebVR cameras available.
  22881. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22882. */
  22883. Camera.prototype._getWebVRProjectionMatrix = function () {
  22884. return BABYLON.Matrix.Identity();
  22885. };
  22886. /**
  22887. * This function MUST be overwritten by the different WebVR cameras available.
  22888. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22889. */
  22890. Camera.prototype._getWebVRViewMatrix = function () {
  22891. return BABYLON.Matrix.Identity();
  22892. };
  22893. Camera.prototype.setCameraRigParameter = function (name, value) {
  22894. if (!this._cameraRigParams) {
  22895. this._cameraRigParams = {};
  22896. }
  22897. this._cameraRigParams[name] = value;
  22898. //provisionnally:
  22899. if (name === "interaxialDistance") {
  22900. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22901. }
  22902. };
  22903. /**
  22904. * needs to be overridden by children so sub has required properties to be copied
  22905. */
  22906. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22907. return null;
  22908. };
  22909. /**
  22910. * May need to be overridden by children
  22911. * @hidden
  22912. */
  22913. Camera.prototype._updateRigCameras = function () {
  22914. for (var i = 0; i < this._rigCameras.length; i++) {
  22915. this._rigCameras[i].minZ = this.minZ;
  22916. this._rigCameras[i].maxZ = this.maxZ;
  22917. this._rigCameras[i].fov = this.fov;
  22918. }
  22919. // only update viewport when ANAGLYPH
  22920. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22921. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22922. }
  22923. };
  22924. /** @hidden */
  22925. Camera.prototype._setupInputs = function () {
  22926. };
  22927. Camera.prototype.serialize = function () {
  22928. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22929. // Type
  22930. serializationObject.type = this.getClassName();
  22931. // Parent
  22932. if (this.parent) {
  22933. serializationObject.parentId = this.parent.id;
  22934. }
  22935. if (this.inputs) {
  22936. this.inputs.serialize(serializationObject);
  22937. }
  22938. // Animations
  22939. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22940. serializationObject.ranges = this.serializeAnimationRanges();
  22941. return serializationObject;
  22942. };
  22943. Camera.prototype.clone = function (name) {
  22944. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22945. };
  22946. Camera.prototype.getDirection = function (localAxis) {
  22947. var result = BABYLON.Vector3.Zero();
  22948. this.getDirectionToRef(localAxis, result);
  22949. return result;
  22950. };
  22951. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22952. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22953. };
  22954. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22955. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22956. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22957. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22958. interaxial_distance: interaxial_distance,
  22959. isStereoscopicSideBySide: isStereoscopicSideBySide
  22960. });
  22961. if (constructorFunc) {
  22962. return constructorFunc;
  22963. }
  22964. // Default to universal camera
  22965. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22966. };
  22967. Camera.prototype.computeWorldMatrix = function () {
  22968. return this.getWorldMatrix();
  22969. };
  22970. Camera.Parse = function (parsedCamera, scene) {
  22971. var type = parsedCamera.type;
  22972. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22973. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22974. // Parent
  22975. if (parsedCamera.parentId) {
  22976. camera._waitingParentId = parsedCamera.parentId;
  22977. }
  22978. //If camera has an input manager, let it parse inputs settings
  22979. if (camera.inputs) {
  22980. camera.inputs.parse(parsedCamera);
  22981. camera._setupInputs();
  22982. }
  22983. if (camera.setPosition) { // need to force position
  22984. camera.position.copyFromFloats(0, 0, 0);
  22985. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22986. }
  22987. // Target
  22988. if (parsedCamera.target) {
  22989. if (camera.setTarget) {
  22990. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22991. }
  22992. }
  22993. // Apply 3d rig, when found
  22994. if (parsedCamera.cameraRigMode) {
  22995. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22996. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22997. }
  22998. // Animations
  22999. if (parsedCamera.animations) {
  23000. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23001. var parsedAnimation = parsedCamera.animations[animationIndex];
  23002. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23003. }
  23004. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23005. }
  23006. if (parsedCamera.autoAnimate) {
  23007. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23008. }
  23009. return camera;
  23010. };
  23011. // Statics
  23012. Camera._PERSPECTIVE_CAMERA = 0;
  23013. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23014. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23015. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23016. Camera._RIG_MODE_NONE = 0;
  23017. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23018. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23019. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23020. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23021. Camera._RIG_MODE_VR = 20;
  23022. Camera._RIG_MODE_WEBVR = 21;
  23023. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23024. Camera.UseAlternateWebVRRendering = false;
  23025. __decorate([
  23026. BABYLON.serializeAsVector3()
  23027. ], Camera.prototype, "position", void 0);
  23028. __decorate([
  23029. BABYLON.serializeAsVector3()
  23030. ], Camera.prototype, "upVector", void 0);
  23031. __decorate([
  23032. BABYLON.serialize()
  23033. ], Camera.prototype, "orthoLeft", void 0);
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Camera.prototype, "orthoRight", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Camera.prototype, "orthoBottom", void 0);
  23040. __decorate([
  23041. BABYLON.serialize()
  23042. ], Camera.prototype, "orthoTop", void 0);
  23043. __decorate([
  23044. BABYLON.serialize()
  23045. ], Camera.prototype, "fov", void 0);
  23046. __decorate([
  23047. BABYLON.serialize()
  23048. ], Camera.prototype, "minZ", void 0);
  23049. __decorate([
  23050. BABYLON.serialize()
  23051. ], Camera.prototype, "maxZ", void 0);
  23052. __decorate([
  23053. BABYLON.serialize()
  23054. ], Camera.prototype, "inertia", void 0);
  23055. __decorate([
  23056. BABYLON.serialize()
  23057. ], Camera.prototype, "mode", void 0);
  23058. __decorate([
  23059. BABYLON.serialize()
  23060. ], Camera.prototype, "layerMask", void 0);
  23061. __decorate([
  23062. BABYLON.serialize()
  23063. ], Camera.prototype, "fovMode", void 0);
  23064. __decorate([
  23065. BABYLON.serialize()
  23066. ], Camera.prototype, "cameraRigMode", void 0);
  23067. __decorate([
  23068. BABYLON.serialize()
  23069. ], Camera.prototype, "interaxialDistance", void 0);
  23070. __decorate([
  23071. BABYLON.serialize()
  23072. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23073. return Camera;
  23074. }(BABYLON.Node));
  23075. BABYLON.Camera = Camera;
  23076. })(BABYLON || (BABYLON = {}));
  23077. //# sourceMappingURL=babylon.camera.js.map
  23078. var BABYLON;
  23079. (function (BABYLON) {
  23080. var RenderingManager = /** @class */ (function () {
  23081. function RenderingManager(scene) {
  23082. /**
  23083. * @hidden
  23084. */
  23085. this._useSceneAutoClearSetup = false;
  23086. this._renderingGroups = new Array();
  23087. this._autoClearDepthStencil = {};
  23088. this._customOpaqueSortCompareFn = {};
  23089. this._customAlphaTestSortCompareFn = {};
  23090. this._customTransparentSortCompareFn = {};
  23091. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23092. this._scene = scene;
  23093. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23094. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23095. }
  23096. }
  23097. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23098. if (depth === void 0) { depth = true; }
  23099. if (stencil === void 0) { stencil = true; }
  23100. if (this._depthStencilBufferAlreadyCleaned) {
  23101. return;
  23102. }
  23103. this._scene.getEngine().clear(null, false, depth, stencil);
  23104. this._depthStencilBufferAlreadyCleaned = true;
  23105. };
  23106. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23107. // Update the observable context (not null as it only goes away on dispose)
  23108. var info = this._renderingGroupInfo;
  23109. info.scene = this._scene;
  23110. info.camera = this._scene.activeCamera;
  23111. // Dispatch sprites
  23112. if (renderSprites) {
  23113. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23114. var manager = this._scene.spriteManagers[index];
  23115. this.dispatchSprites(manager);
  23116. }
  23117. }
  23118. // Render
  23119. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23120. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23121. var renderingGroup = this._renderingGroups[index];
  23122. if (!renderingGroup)
  23123. continue;
  23124. var renderingGroupMask = Math.pow(2, index);
  23125. info.renderingGroupId = index;
  23126. // Before Observable
  23127. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23128. // Clear depth/stencil if needed
  23129. if (RenderingManager.AUTOCLEAR) {
  23130. var autoClear = this._useSceneAutoClearSetup ?
  23131. this._scene.getAutoClearDepthStencilSetup(index) :
  23132. this._autoClearDepthStencil[index];
  23133. if (autoClear && autoClear.autoClear) {
  23134. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23135. }
  23136. }
  23137. // Render
  23138. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23139. var step = _a[_i];
  23140. step.action(index);
  23141. }
  23142. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23143. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23144. var step = _c[_b];
  23145. step.action(index);
  23146. }
  23147. // After Observable
  23148. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23149. }
  23150. };
  23151. RenderingManager.prototype.reset = function () {
  23152. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23153. var renderingGroup = this._renderingGroups[index];
  23154. if (renderingGroup) {
  23155. renderingGroup.prepare();
  23156. }
  23157. }
  23158. };
  23159. RenderingManager.prototype.dispose = function () {
  23160. this.freeRenderingGroups();
  23161. this._renderingGroups.length = 0;
  23162. this._renderingGroupInfo = null;
  23163. };
  23164. /**
  23165. * Clear the info related to rendering groups preventing retention points during dispose.
  23166. */
  23167. RenderingManager.prototype.freeRenderingGroups = function () {
  23168. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23169. var renderingGroup = this._renderingGroups[index];
  23170. if (renderingGroup) {
  23171. renderingGroup.dispose();
  23172. }
  23173. }
  23174. };
  23175. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23176. if (this._renderingGroups[renderingGroupId] === undefined) {
  23177. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23178. }
  23179. };
  23180. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23181. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23182. this._prepareRenderingGroup(renderingGroupId);
  23183. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23184. };
  23185. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23186. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23187. this._prepareRenderingGroup(renderingGroupId);
  23188. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23189. };
  23190. /**
  23191. * @param subMesh The submesh to dispatch
  23192. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23193. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23194. */
  23195. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23196. if (mesh === undefined) {
  23197. mesh = subMesh.getMesh();
  23198. }
  23199. var renderingGroupId = mesh.renderingGroupId || 0;
  23200. this._prepareRenderingGroup(renderingGroupId);
  23201. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23202. };
  23203. /**
  23204. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23205. * This allowed control for front to back rendering or reversly depending of the special needs.
  23206. *
  23207. * @param renderingGroupId The rendering group id corresponding to its index
  23208. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23209. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23210. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23211. */
  23212. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23213. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23214. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23215. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23216. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23217. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23218. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23219. if (this._renderingGroups[renderingGroupId]) {
  23220. var group = this._renderingGroups[renderingGroupId];
  23221. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23222. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23223. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23224. }
  23225. };
  23226. /**
  23227. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23228. *
  23229. * @param renderingGroupId The rendering group id corresponding to its index
  23230. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23231. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23232. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23233. */
  23234. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23235. if (depth === void 0) { depth = true; }
  23236. if (stencil === void 0) { stencil = true; }
  23237. this._autoClearDepthStencil[renderingGroupId] = {
  23238. autoClear: autoClearDepthStencil,
  23239. depth: depth,
  23240. stencil: stencil
  23241. };
  23242. };
  23243. /**
  23244. * Gets the current auto clear configuration for one rendering group of the rendering
  23245. * manager.
  23246. * @param index the rendering group index to get the information for
  23247. * @returns The auto clear setup for the requested rendering group
  23248. */
  23249. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23250. return this._autoClearDepthStencil[index];
  23251. };
  23252. /**
  23253. * The max id used for rendering groups (not included)
  23254. */
  23255. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23256. /**
  23257. * The min id used for rendering groups (included)
  23258. */
  23259. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23260. /**
  23261. * Used to globally prevent autoclearing scenes.
  23262. */
  23263. RenderingManager.AUTOCLEAR = true;
  23264. return RenderingManager;
  23265. }());
  23266. BABYLON.RenderingManager = RenderingManager;
  23267. })(BABYLON || (BABYLON = {}));
  23268. //# sourceMappingURL=babylon.renderingManager.js.map
  23269. var BABYLON;
  23270. (function (BABYLON) {
  23271. var RenderingGroup = /** @class */ (function () {
  23272. /**
  23273. * Creates a new rendering group.
  23274. * @param index The rendering group index
  23275. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23276. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23277. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23278. */
  23279. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23280. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23281. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23282. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23283. this.index = index;
  23284. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23285. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23286. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23287. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23288. this._particleSystems = new BABYLON.SmartArray(256);
  23289. this._spriteManagers = new BABYLON.SmartArray(256);
  23290. this._edgesRenderers = new BABYLON.SmartArray(16);
  23291. this._scene = scene;
  23292. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23293. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23294. this.transparentSortCompareFn = transparentSortCompareFn;
  23295. }
  23296. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23297. /**
  23298. * Set the opaque sort comparison function.
  23299. * If null the sub meshes will be render in the order they were created
  23300. */
  23301. set: function (value) {
  23302. this._opaqueSortCompareFn = value;
  23303. if (value) {
  23304. this._renderOpaque = this.renderOpaqueSorted;
  23305. }
  23306. else {
  23307. this._renderOpaque = RenderingGroup.renderUnsorted;
  23308. }
  23309. },
  23310. enumerable: true,
  23311. configurable: true
  23312. });
  23313. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23314. /**
  23315. * Set the alpha test sort comparison function.
  23316. * If null the sub meshes will be render in the order they were created
  23317. */
  23318. set: function (value) {
  23319. this._alphaTestSortCompareFn = value;
  23320. if (value) {
  23321. this._renderAlphaTest = this.renderAlphaTestSorted;
  23322. }
  23323. else {
  23324. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23325. }
  23326. },
  23327. enumerable: true,
  23328. configurable: true
  23329. });
  23330. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23331. /**
  23332. * Set the transparent sort comparison function.
  23333. * If null the sub meshes will be render in the order they were created
  23334. */
  23335. set: function (value) {
  23336. if (value) {
  23337. this._transparentSortCompareFn = value;
  23338. }
  23339. else {
  23340. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23341. }
  23342. this._renderTransparent = this.renderTransparentSorted;
  23343. },
  23344. enumerable: true,
  23345. configurable: true
  23346. });
  23347. /**
  23348. * Render all the sub meshes contained in the group.
  23349. * @param customRenderFunction Used to override the default render behaviour of the group.
  23350. * @returns true if rendered some submeshes.
  23351. */
  23352. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23353. if (customRenderFunction) {
  23354. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23355. return;
  23356. }
  23357. var engine = this._scene.getEngine();
  23358. // Depth only
  23359. if (this._depthOnlySubMeshes.length !== 0) {
  23360. engine.setColorWrite(false);
  23361. this._renderAlphaTest(this._depthOnlySubMeshes);
  23362. engine.setColorWrite(true);
  23363. }
  23364. // Opaque
  23365. if (this._opaqueSubMeshes.length !== 0) {
  23366. this._renderOpaque(this._opaqueSubMeshes);
  23367. }
  23368. // Alpha test
  23369. if (this._alphaTestSubMeshes.length !== 0) {
  23370. this._renderAlphaTest(this._alphaTestSubMeshes);
  23371. }
  23372. var stencilState = engine.getStencilBuffer();
  23373. engine.setStencilBuffer(false);
  23374. // Sprites
  23375. if (renderSprites) {
  23376. this._renderSprites();
  23377. }
  23378. // Particles
  23379. if (renderParticles) {
  23380. this._renderParticles(activeMeshes);
  23381. }
  23382. if (this.onBeforeTransparentRendering) {
  23383. this.onBeforeTransparentRendering();
  23384. }
  23385. // Transparent
  23386. if (this._transparentSubMeshes.length !== 0) {
  23387. this._renderTransparent(this._transparentSubMeshes);
  23388. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23389. }
  23390. // Set back stencil to false in case it changes before the edge renderer.
  23391. engine.setStencilBuffer(false);
  23392. // Edges
  23393. if (this._edgesRenderers.length) {
  23394. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23395. this._edgesRenderers.data[edgesRendererIndex].render();
  23396. }
  23397. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23398. }
  23399. // Restore Stencil state.
  23400. engine.setStencilBuffer(stencilState);
  23401. };
  23402. /**
  23403. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23404. * @param subMeshes The submeshes to render
  23405. */
  23406. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23407. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23408. };
  23409. /**
  23410. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23411. * @param subMeshes The submeshes to render
  23412. */
  23413. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23414. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23415. };
  23416. /**
  23417. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23418. * @param subMeshes The submeshes to render
  23419. */
  23420. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23421. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23422. };
  23423. /**
  23424. * Renders the submeshes in a specified order.
  23425. * @param subMeshes The submeshes to sort before render
  23426. * @param sortCompareFn The comparison function use to sort
  23427. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23428. * @param transparent Specifies to activate blending if true
  23429. */
  23430. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23431. var subIndex = 0;
  23432. var subMesh;
  23433. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23434. for (; subIndex < subMeshes.length; subIndex++) {
  23435. subMesh = subMeshes.data[subIndex];
  23436. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23437. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23438. }
  23439. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23440. if (sortCompareFn) {
  23441. sortedArray.sort(sortCompareFn);
  23442. }
  23443. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23444. subMesh = sortedArray[subIndex];
  23445. if (transparent) {
  23446. var material = subMesh.getMaterial();
  23447. if (material && material.needDepthPrePass) {
  23448. var engine = material.getScene().getEngine();
  23449. engine.setColorWrite(false);
  23450. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23451. subMesh.render(false);
  23452. engine.setColorWrite(true);
  23453. }
  23454. }
  23455. subMesh.render(transparent);
  23456. }
  23457. };
  23458. /**
  23459. * Renders the submeshes in the order they were dispatched (no sort applied).
  23460. * @param subMeshes The submeshes to render
  23461. */
  23462. RenderingGroup.renderUnsorted = function (subMeshes) {
  23463. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23464. var submesh = subMeshes.data[subIndex];
  23465. submesh.render(false);
  23466. }
  23467. };
  23468. /**
  23469. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23470. * are rendered back to front if in the same alpha index.
  23471. *
  23472. * @param a The first submesh
  23473. * @param b The second submesh
  23474. * @returns The result of the comparison
  23475. */
  23476. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23477. // Alpha index first
  23478. if (a._alphaIndex > b._alphaIndex) {
  23479. return 1;
  23480. }
  23481. if (a._alphaIndex < b._alphaIndex) {
  23482. return -1;
  23483. }
  23484. // Then distance to camera
  23485. return RenderingGroup.backToFrontSortCompare(a, b);
  23486. };
  23487. /**
  23488. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23489. * are rendered back to front.
  23490. *
  23491. * @param a The first submesh
  23492. * @param b The second submesh
  23493. * @returns The result of the comparison
  23494. */
  23495. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23496. // Then distance to camera
  23497. if (a._distanceToCamera < b._distanceToCamera) {
  23498. return 1;
  23499. }
  23500. if (a._distanceToCamera > b._distanceToCamera) {
  23501. return -1;
  23502. }
  23503. return 0;
  23504. };
  23505. /**
  23506. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23507. * are rendered front to back (prevent overdraw).
  23508. *
  23509. * @param a The first submesh
  23510. * @param b The second submesh
  23511. * @returns The result of the comparison
  23512. */
  23513. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23514. // Then distance to camera
  23515. if (a._distanceToCamera < b._distanceToCamera) {
  23516. return -1;
  23517. }
  23518. if (a._distanceToCamera > b._distanceToCamera) {
  23519. return 1;
  23520. }
  23521. return 0;
  23522. };
  23523. /**
  23524. * Resets the different lists of submeshes to prepare a new frame.
  23525. */
  23526. RenderingGroup.prototype.prepare = function () {
  23527. this._opaqueSubMeshes.reset();
  23528. this._transparentSubMeshes.reset();
  23529. this._alphaTestSubMeshes.reset();
  23530. this._depthOnlySubMeshes.reset();
  23531. this._particleSystems.reset();
  23532. this._spriteManagers.reset();
  23533. this._edgesRenderers.reset();
  23534. };
  23535. RenderingGroup.prototype.dispose = function () {
  23536. this._opaqueSubMeshes.dispose();
  23537. this._transparentSubMeshes.dispose();
  23538. this._alphaTestSubMeshes.dispose();
  23539. this._depthOnlySubMeshes.dispose();
  23540. this._particleSystems.dispose();
  23541. this._spriteManagers.dispose();
  23542. this._edgesRenderers.dispose();
  23543. };
  23544. /**
  23545. * Inserts the submesh in its correct queue depending on its material.
  23546. * @param subMesh The submesh to dispatch
  23547. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23548. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23549. */
  23550. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23551. // Get mesh and materials if not provided
  23552. if (mesh === undefined) {
  23553. mesh = subMesh.getMesh();
  23554. }
  23555. if (material === undefined) {
  23556. material = subMesh.getMaterial();
  23557. }
  23558. if (material === null || material === undefined) {
  23559. return;
  23560. }
  23561. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23562. this._transparentSubMeshes.push(subMesh);
  23563. }
  23564. else if (material.needAlphaTesting()) { // Alpha test
  23565. if (material.needDepthPrePass) {
  23566. this._depthOnlySubMeshes.push(subMesh);
  23567. }
  23568. this._alphaTestSubMeshes.push(subMesh);
  23569. }
  23570. else {
  23571. if (material.needDepthPrePass) {
  23572. this._depthOnlySubMeshes.push(subMesh);
  23573. }
  23574. this._opaqueSubMeshes.push(subMesh); // Opaque
  23575. }
  23576. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23577. this._edgesRenderers.push(mesh._edgesRenderer);
  23578. }
  23579. };
  23580. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23581. this._spriteManagers.push(spriteManager);
  23582. };
  23583. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23584. this._particleSystems.push(particleSystem);
  23585. };
  23586. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23587. if (this._particleSystems.length === 0) {
  23588. return;
  23589. }
  23590. // Particles
  23591. var activeCamera = this._scene.activeCamera;
  23592. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23593. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23594. var particleSystem = this._particleSystems.data[particleIndex];
  23595. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23596. continue;
  23597. }
  23598. var emitter = particleSystem.emitter;
  23599. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23600. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23601. }
  23602. }
  23603. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23604. };
  23605. RenderingGroup.prototype._renderSprites = function () {
  23606. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23607. return;
  23608. }
  23609. // Sprites
  23610. var activeCamera = this._scene.activeCamera;
  23611. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23612. for (var id = 0; id < this._spriteManagers.length; id++) {
  23613. var spriteManager = this._spriteManagers.data[id];
  23614. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23615. spriteManager.render();
  23616. }
  23617. }
  23618. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23619. };
  23620. return RenderingGroup;
  23621. }());
  23622. BABYLON.RenderingGroup = RenderingGroup;
  23623. })(BABYLON || (BABYLON = {}));
  23624. //# sourceMappingURL=babylon.renderingGroup.js.map
  23625. var BABYLON;
  23626. (function (BABYLON) {
  23627. /**
  23628. * Groups all the scene component constants in one place to ease maintenance.
  23629. * @hidden
  23630. */
  23631. var SceneComponentConstants = /** @class */ (function () {
  23632. function SceneComponentConstants() {
  23633. }
  23634. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23635. SceneComponentConstants.NAME_LAYER = "Layer";
  23636. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23637. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23638. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23639. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23640. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23641. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23642. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23643. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23644. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23645. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23646. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23647. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23648. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23649. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23650. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23651. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23652. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23653. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23654. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23655. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23656. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23657. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23658. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23659. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 0;
  23660. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 1;
  23661. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 2;
  23662. SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER = 0;
  23663. return SceneComponentConstants;
  23664. }());
  23665. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23666. /**
  23667. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23668. * @hidden
  23669. */
  23670. var Stage = /** @class */ (function (_super) {
  23671. __extends(Stage, _super);
  23672. /**
  23673. * Hide ctor from the rest of the world.
  23674. * @param items The items to add.
  23675. */
  23676. function Stage(items) {
  23677. return _super.apply(this, items) || this;
  23678. }
  23679. /**
  23680. * Creates a new Stage.
  23681. * @returns A new instance of a Stage
  23682. */
  23683. Stage.Create = function () {
  23684. return Object.create(Stage.prototype);
  23685. };
  23686. /**
  23687. * Registers a step in an ordered way in the targeted stage.
  23688. * @param index Defines the position to register the step in
  23689. * @param component Defines the component attached to the step
  23690. * @param action Defines the action to launch during the step
  23691. */
  23692. Stage.prototype.registerStep = function (index, component, action) {
  23693. var i = 0;
  23694. var maxIndex = Number.MAX_VALUE;
  23695. for (; i < this.length && i < maxIndex; i++) {
  23696. var step = this[i];
  23697. maxIndex = step.index;
  23698. }
  23699. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23700. };
  23701. /**
  23702. * Clears all the steps from the stage.
  23703. */
  23704. Stage.prototype.clear = function () {
  23705. this.length = 0;
  23706. };
  23707. return Stage;
  23708. }(Array));
  23709. BABYLON.Stage = Stage;
  23710. })(BABYLON || (BABYLON = {}));
  23711. //# sourceMappingURL=babylon.sceneComponent.js.map
  23712. var BABYLON;
  23713. (function (BABYLON) {
  23714. /**
  23715. * Base class of the scene acting as a container for the different elements composing a scene.
  23716. * This class is dynamically extended by the different components of the scene increasing
  23717. * flexibility and reducing coupling
  23718. */
  23719. var AbstractScene = /** @class */ (function () {
  23720. function AbstractScene() {
  23721. /** All of the cameras added to this scene
  23722. * @see http://doc.babylonjs.com/babylon101/cameras
  23723. */
  23724. this.cameras = new Array();
  23725. /**
  23726. * All of the lights added to this scene
  23727. * @see http://doc.babylonjs.com/babylon101/lights
  23728. */
  23729. this.lights = new Array();
  23730. /**
  23731. * All of the (abstract) meshes added to this scene
  23732. */
  23733. this.meshes = new Array();
  23734. /**
  23735. * The list of skeletons added to the scene
  23736. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23737. */
  23738. this.skeletons = new Array();
  23739. /**
  23740. * All of the particle systems added to this scene
  23741. * @see http://doc.babylonjs.com/babylon101/particles
  23742. */
  23743. this.particleSystems = new Array();
  23744. /**
  23745. * Gets a list of Animations associated with the scene
  23746. */
  23747. this.animations = [];
  23748. /**
  23749. * All of the animation groups added to this scene
  23750. * @see http://doc.babylonjs.com/how_to/group
  23751. */
  23752. this.animationGroups = new Array();
  23753. /**
  23754. * All of the multi-materials added to this scene
  23755. * @see http://doc.babylonjs.com/how_to/multi_materials
  23756. */
  23757. this.multiMaterials = new Array();
  23758. /**
  23759. * All of the materials added to this scene
  23760. * @see http://doc.babylonjs.com/babylon101/materials
  23761. */
  23762. this.materials = new Array();
  23763. /**
  23764. * The list of morph target managers added to the scene
  23765. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23766. */
  23767. this.morphTargetManagers = new Array();
  23768. /**
  23769. * The list of geometries used in the scene.
  23770. */
  23771. this.geometries = new Array();
  23772. /**
  23773. * All of the tranform nodes added to this scene
  23774. * @see http://doc.babylonjs.com/how_to/transformnode
  23775. */
  23776. this.transformNodes = new Array();
  23777. /**
  23778. * ActionManagers available on the scene.
  23779. */
  23780. this.actionManagers = new Array();
  23781. /**
  23782. * Sounds to keep.
  23783. */
  23784. this.sounds = new Array();
  23785. /**
  23786. * Textures to keep.
  23787. */
  23788. this.textures = new Array();
  23789. }
  23790. /**
  23791. * Adds a parser in the list of available ones
  23792. * @param name Defines the name of the parser
  23793. * @param parser Defines the parser to add
  23794. */
  23795. AbstractScene.AddParser = function (name, parser) {
  23796. this._BabylonFileParsers[name] = parser;
  23797. };
  23798. /**
  23799. * Gets a general parser from the list of avaialble ones
  23800. * @param name Defines the name of the parser
  23801. * @returns the requested parser or null
  23802. */
  23803. AbstractScene.GetParser = function (name) {
  23804. if (this._BabylonFileParsers[name]) {
  23805. return this._BabylonFileParsers[name];
  23806. }
  23807. return null;
  23808. };
  23809. /**
  23810. * Adds n individual parser in the list of available ones
  23811. * @param name Defines the name of the parser
  23812. * @param parser Defines the parser to add
  23813. */
  23814. AbstractScene.AddIndividualParser = function (name, parser) {
  23815. this._IndividualBabylonFileParsers[name] = parser;
  23816. };
  23817. /**
  23818. * Gets an individual parser from the list of avaialble ones
  23819. * @param name Defines the name of the parser
  23820. * @returns the requested parser or null
  23821. */
  23822. AbstractScene.GetIndividualParser = function (name) {
  23823. if (this._IndividualBabylonFileParsers[name]) {
  23824. return this._IndividualBabylonFileParsers[name];
  23825. }
  23826. return null;
  23827. };
  23828. /**
  23829. * Parser json data and populate both a scene and its associated container object
  23830. * @param jsonData Defines the data to parse
  23831. * @param scene Defines the scene to parse the data for
  23832. * @param container Defines the container attached to the parsing sequence
  23833. * @param rootUrl Defines the root url of the data
  23834. */
  23835. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23836. for (var parserName in this._BabylonFileParsers) {
  23837. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23838. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23839. }
  23840. }
  23841. };
  23842. /**
  23843. * Stores the list of available parsers in the application.
  23844. */
  23845. AbstractScene._BabylonFileParsers = {};
  23846. /**
  23847. * Stores the list of available individual parsers in the application.
  23848. */
  23849. AbstractScene._IndividualBabylonFileParsers = {};
  23850. return AbstractScene;
  23851. }());
  23852. BABYLON.AbstractScene = AbstractScene;
  23853. })(BABYLON || (BABYLON = {}));
  23854. //# sourceMappingURL=babylon.abstractScene.js.map
  23855. var BABYLON;
  23856. (function (BABYLON) {
  23857. /** @hidden */
  23858. var ClickInfo = /** @class */ (function () {
  23859. function ClickInfo() {
  23860. this._singleClick = false;
  23861. this._doubleClick = false;
  23862. this._hasSwiped = false;
  23863. this._ignore = false;
  23864. }
  23865. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23866. get: function () {
  23867. return this._singleClick;
  23868. },
  23869. set: function (b) {
  23870. this._singleClick = b;
  23871. },
  23872. enumerable: true,
  23873. configurable: true
  23874. });
  23875. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23876. get: function () {
  23877. return this._doubleClick;
  23878. },
  23879. set: function (b) {
  23880. this._doubleClick = b;
  23881. },
  23882. enumerable: true,
  23883. configurable: true
  23884. });
  23885. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23886. get: function () {
  23887. return this._hasSwiped;
  23888. },
  23889. set: function (b) {
  23890. this._hasSwiped = b;
  23891. },
  23892. enumerable: true,
  23893. configurable: true
  23894. });
  23895. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23896. get: function () {
  23897. return this._ignore;
  23898. },
  23899. set: function (b) {
  23900. this._ignore = b;
  23901. },
  23902. enumerable: true,
  23903. configurable: true
  23904. });
  23905. return ClickInfo;
  23906. }());
  23907. /**
  23908. * This class is used by the onRenderingGroupObservable
  23909. */
  23910. var RenderingGroupInfo = /** @class */ (function () {
  23911. function RenderingGroupInfo() {
  23912. }
  23913. return RenderingGroupInfo;
  23914. }());
  23915. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23916. /**
  23917. * Represents a scene to be rendered by the engine.
  23918. * @see http://doc.babylonjs.com/features/scene
  23919. */
  23920. var Scene = /** @class */ (function (_super) {
  23921. __extends(Scene, _super);
  23922. /**
  23923. * Creates a new Scene
  23924. * @param engine defines the engine to use to render this scene
  23925. */
  23926. function Scene(engine) {
  23927. var _this = _super.call(this) || this;
  23928. // Members
  23929. /**
  23930. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23931. */
  23932. _this.autoClear = true;
  23933. /**
  23934. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23935. */
  23936. _this.autoClearDepthAndStencil = true;
  23937. /**
  23938. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23939. */
  23940. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23941. /**
  23942. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23943. */
  23944. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23945. _this._forceWireframe = false;
  23946. _this._forcePointsCloud = false;
  23947. /**
  23948. * Gets or sets a boolean indicating if animations are enabled
  23949. */
  23950. _this.animationsEnabled = true;
  23951. _this._animationPropertiesOverride = null;
  23952. /**
  23953. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23954. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23955. */
  23956. _this.useConstantAnimationDeltaTime = false;
  23957. /**
  23958. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23959. * Please note that it requires to run a ray cast through the scene on every frame
  23960. */
  23961. _this.constantlyUpdateMeshUnderPointer = false;
  23962. /**
  23963. * Defines the HTML cursor to use when hovering over interactive elements
  23964. */
  23965. _this.hoverCursor = "pointer";
  23966. /**
  23967. * Defines the HTML default cursor to use (empty by default)
  23968. */
  23969. _this.defaultCursor = "";
  23970. /**
  23971. * This is used to call preventDefault() on pointer down
  23972. * in order to block unwanted artifacts like system double clicks
  23973. */
  23974. _this.preventDefaultOnPointerDown = true;
  23975. // Metadata
  23976. /**
  23977. * Gets or sets user defined metadata
  23978. */
  23979. _this.metadata = null;
  23980. /**
  23981. * Use this array to add regular expressions used to disable offline support for specific urls
  23982. */
  23983. _this.disableOfflineSupportExceptionRules = new Array();
  23984. /**
  23985. * An event triggered when the scene is disposed.
  23986. */
  23987. _this.onDisposeObservable = new BABYLON.Observable();
  23988. _this._onDisposeObserver = null;
  23989. /**
  23990. * An event triggered before rendering the scene (right after animations and physics)
  23991. */
  23992. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23993. _this._onBeforeRenderObserver = null;
  23994. /**
  23995. * An event triggered after rendering the scene
  23996. */
  23997. _this.onAfterRenderObservable = new BABYLON.Observable();
  23998. _this._onAfterRenderObserver = null;
  23999. /**
  24000. * An event triggered before animating the scene
  24001. */
  24002. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24003. /**
  24004. * An event triggered after animations processing
  24005. */
  24006. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24007. /**
  24008. * An event triggered before draw calls are ready to be sent
  24009. */
  24010. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24011. /**
  24012. * An event triggered after draw calls have been sent
  24013. */
  24014. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24015. /**
  24016. * An event triggered when physic simulation is about to be run
  24017. */
  24018. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24019. /**
  24020. * An event triggered when physic simulation has been done
  24021. */
  24022. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24023. /**
  24024. * An event triggered when the scene is ready
  24025. */
  24026. _this.onReadyObservable = new BABYLON.Observable();
  24027. /**
  24028. * An event triggered before rendering a camera
  24029. */
  24030. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24031. _this._onBeforeCameraRenderObserver = null;
  24032. /**
  24033. * An event triggered after rendering a camera
  24034. */
  24035. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24036. _this._onAfterCameraRenderObserver = null;
  24037. /**
  24038. * An event triggered when active meshes evaluation is about to start
  24039. */
  24040. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when active meshes evaluation is done
  24043. */
  24044. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24045. /**
  24046. * An event triggered when particles rendering is about to start
  24047. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24048. */
  24049. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when particles rendering is done
  24052. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24053. */
  24054. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24055. /**
  24056. * An event triggered when sprites rendering is about to start
  24057. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24058. */
  24059. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24060. /**
  24061. * An event triggered when sprites rendering is done
  24062. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24063. */
  24064. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24065. /**
  24066. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24067. */
  24068. _this.onDataLoadedObservable = new BABYLON.Observable();
  24069. /**
  24070. * An event triggered when a camera is created
  24071. */
  24072. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24073. /**
  24074. * An event triggered when a camera is removed
  24075. */
  24076. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24077. /**
  24078. * An event triggered when a light is created
  24079. */
  24080. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24081. /**
  24082. * An event triggered when a light is removed
  24083. */
  24084. _this.onLightRemovedObservable = new BABYLON.Observable();
  24085. /**
  24086. * An event triggered when a geometry is created
  24087. */
  24088. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24089. /**
  24090. * An event triggered when a geometry is removed
  24091. */
  24092. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24093. /**
  24094. * An event triggered when a transform node is created
  24095. */
  24096. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24097. /**
  24098. * An event triggered when a transform node is removed
  24099. */
  24100. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24101. /**
  24102. * An event triggered when a mesh is created
  24103. */
  24104. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24105. /**
  24106. * An event triggered when a mesh is removed
  24107. */
  24108. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24109. /**
  24110. * An event triggered when render targets are about to be rendered
  24111. * Can happen multiple times per frame.
  24112. */
  24113. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24114. /**
  24115. * An event triggered when render targets were rendered.
  24116. * Can happen multiple times per frame.
  24117. */
  24118. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24119. /**
  24120. * An event triggered before calculating deterministic simulation step
  24121. */
  24122. _this.onBeforeStepObservable = new BABYLON.Observable();
  24123. /**
  24124. * An event triggered after calculating deterministic simulation step
  24125. */
  24126. _this.onAfterStepObservable = new BABYLON.Observable();
  24127. /**
  24128. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24129. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24130. * 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)
  24131. */
  24132. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24133. /**
  24134. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24135. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24136. * 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)
  24137. */
  24138. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24139. // Animations
  24140. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24141. /**
  24142. * 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).
  24143. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24144. */
  24145. _this.onPrePointerObservable = new BABYLON.Observable();
  24146. /**
  24147. * Observable event triggered each time an input event is received from the rendering canvas
  24148. */
  24149. _this.onPointerObservable = new BABYLON.Observable();
  24150. _this._meshPickProceed = false;
  24151. _this._currentPickResult = null;
  24152. _this._previousPickResult = null;
  24153. _this._totalPointersPressed = 0;
  24154. _this._doubleClickOccured = false;
  24155. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24156. _this.cameraToUseForPointers = null;
  24157. _this._pointerX = 0;
  24158. _this._pointerY = 0;
  24159. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24160. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24161. _this._startingPointerTime = 0;
  24162. _this._previousStartingPointerTime = 0;
  24163. _this._pointerCaptures = {};
  24164. // Deterministic lockstep
  24165. _this._timeAccumulator = 0;
  24166. _this._currentStepId = 0;
  24167. _this._currentInternalStep = 0;
  24168. // Keyboard
  24169. /**
  24170. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24171. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24172. */
  24173. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24174. /**
  24175. * Observable event triggered each time an keyboard event is received from the hosting window
  24176. */
  24177. _this.onKeyboardObservable = new BABYLON.Observable();
  24178. // Coordinates system
  24179. _this._useRightHandedSystem = false;
  24180. // Fog
  24181. _this._fogEnabled = true;
  24182. _this._fogMode = Scene.FOGMODE_NONE;
  24183. /**
  24184. * Gets or sets the fog color to use
  24185. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24186. */
  24187. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24188. /**
  24189. * Gets or sets the fog density to use
  24190. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24191. */
  24192. _this.fogDensity = 0.1;
  24193. /**
  24194. * Gets or sets the fog start distance to use
  24195. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24196. */
  24197. _this.fogStart = 0;
  24198. /**
  24199. * Gets or sets the fog end distance to use
  24200. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24201. */
  24202. _this.fogEnd = 1000.0;
  24203. // Lights
  24204. _this._shadowsEnabled = true;
  24205. _this._lightsEnabled = true;
  24206. /** All of the active cameras added to this scene. */
  24207. _this.activeCameras = new Array();
  24208. // Textures
  24209. _this._texturesEnabled = true;
  24210. // Particles
  24211. /**
  24212. * Gets or sets a boolean indicating if particles are enabled on this scene
  24213. */
  24214. _this.particlesEnabled = true;
  24215. // Sprites
  24216. /**
  24217. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24218. */
  24219. _this.spritesEnabled = true;
  24220. /**
  24221. * All of the sprite managers added to this scene
  24222. * @see http://doc.babylonjs.com/babylon101/sprites
  24223. */
  24224. _this.spriteManagers = new Array();
  24225. // Skeletons
  24226. _this._skeletonsEnabled = true;
  24227. // Lens flares
  24228. /**
  24229. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24230. */
  24231. _this.lensFlaresEnabled = true;
  24232. // Collisions
  24233. /**
  24234. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24235. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24236. */
  24237. _this.collisionsEnabled = true;
  24238. /**
  24239. * Defines the gravity applied to this scene (used only for collisions)
  24240. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24241. */
  24242. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24243. // Postprocesses
  24244. /**
  24245. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24246. */
  24247. _this.postProcessesEnabled = true;
  24248. /**
  24249. * The list of postprocesses added to the scene
  24250. */
  24251. _this.postProcesses = new Array();
  24252. // Customs render targets
  24253. /**
  24254. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24255. */
  24256. _this.renderTargetsEnabled = true;
  24257. /**
  24258. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24259. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24260. */
  24261. _this.dumpNextRenderTargets = false;
  24262. /**
  24263. * The list of user defined render targets added to the scene
  24264. */
  24265. _this.customRenderTargets = new Array();
  24266. /**
  24267. * Gets the list of meshes imported to the scene through SceneLoader
  24268. */
  24269. _this.importedMeshesFiles = new Array();
  24270. // Probes
  24271. /**
  24272. * Gets or sets a boolean indicating if probes are enabled on this scene
  24273. */
  24274. _this.probesEnabled = true;
  24275. /**
  24276. * The list of reflection probes added to the scene
  24277. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24278. */
  24279. _this.reflectionProbes = new Array();
  24280. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24281. // Procedural textures
  24282. /**
  24283. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24284. */
  24285. _this.proceduralTexturesEnabled = true;
  24286. /**
  24287. * The list of procedural textures added to the scene
  24288. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24289. */
  24290. _this.proceduralTextures = new Array();
  24291. /**
  24292. * The list of sound tracks added to the scene
  24293. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24294. */
  24295. _this.soundTracks = new Array();
  24296. _this._audioEnabled = true;
  24297. _this._headphone = false;
  24298. // Performance counters
  24299. _this._totalVertices = new BABYLON.PerfCounter();
  24300. /** @hidden */
  24301. _this._activeIndices = new BABYLON.PerfCounter();
  24302. /** @hidden */
  24303. _this._activeParticles = new BABYLON.PerfCounter();
  24304. /** @hidden */
  24305. _this._activeBones = new BABYLON.PerfCounter();
  24306. _this._animationTime = 0;
  24307. /**
  24308. * Gets or sets a general scale for animation speed
  24309. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24310. */
  24311. _this.animationTimeScale = 1;
  24312. _this._renderId = 0;
  24313. _this._executeWhenReadyTimeoutId = -1;
  24314. _this._intermediateRendering = false;
  24315. _this._viewUpdateFlag = -1;
  24316. _this._projectionUpdateFlag = -1;
  24317. _this._alternateViewUpdateFlag = -1;
  24318. _this._alternateProjectionUpdateFlag = -1;
  24319. /** @hidden */
  24320. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24321. _this._activeRequests = new Array();
  24322. _this._pendingData = new Array();
  24323. _this._isDisposed = false;
  24324. /**
  24325. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24326. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24327. */
  24328. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24329. _this._activeMeshes = new BABYLON.SmartArray(256);
  24330. _this._processedMaterials = new BABYLON.SmartArray(256);
  24331. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24332. /** @hidden */
  24333. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24334. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24335. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24336. /** @hidden */
  24337. _this._activeAnimatables = new Array();
  24338. _this._transformMatrix = BABYLON.Matrix.Zero();
  24339. _this._useAlternateCameraConfiguration = false;
  24340. _this._alternateRendering = false;
  24341. /**
  24342. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24343. * This is useful if there are more lights that the maximum simulteanous authorized
  24344. */
  24345. _this.requireLightSorting = false;
  24346. /**
  24347. * @hidden
  24348. * Backing store of defined scene components.
  24349. */
  24350. _this._components = [];
  24351. /**
  24352. * @hidden
  24353. * Backing store of defined scene components.
  24354. */
  24355. _this._serializableComponents = [];
  24356. /**
  24357. * List of components to register on the next registration step.
  24358. */
  24359. _this._transientComponents = [];
  24360. /**
  24361. * @hidden
  24362. * Defines the actions happening before camera updates.
  24363. */
  24364. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24365. /**
  24366. * @hidden
  24367. * Defines the actions happening before camera updates.
  24368. */
  24369. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24370. /**
  24371. * @hidden
  24372. * Defines the actions happening during the per mesh ready checks.
  24373. */
  24374. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24375. /**
  24376. * @hidden
  24377. * Defines the actions happening before evaluate active mesh checks.
  24378. */
  24379. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24380. /**
  24381. * @hidden
  24382. * Defines the actions happening during the evaluate sub mesh checks.
  24383. */
  24384. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24385. /**
  24386. * @hidden
  24387. * Defines the actions happening during the active mesh stage.
  24388. */
  24389. _this._activeMeshStage = BABYLON.Stage.Create();
  24390. /**
  24391. * @hidden
  24392. * Defines the actions happening during the per camera render target step.
  24393. */
  24394. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24395. /**
  24396. * @hidden
  24397. * Defines the actions happening just before the active camera is drawing.
  24398. */
  24399. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24400. /**
  24401. * Defines the actions happening just before a rendering group is drawing.
  24402. */
  24403. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24404. /**
  24405. * @hidden
  24406. * Defines the actions happening just after a rendering group has been drawn.
  24407. */
  24408. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24409. /**
  24410. * @hidden
  24411. * Defines the actions happening just after the active camera has been drawn.
  24412. */
  24413. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24414. /**
  24415. * @hidden
  24416. * Defines the actions happening when Geometries are rebuilding.
  24417. */
  24418. _this._rebuildGeometryStage = BABYLON.Stage.Create();
  24419. _this._activeMeshesFrozen = false;
  24420. /** @hidden */
  24421. _this._allowPostProcessClear = true;
  24422. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24423. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24424. _this.blockMaterialDirtyMechanism = false;
  24425. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24426. _this._engine.scenes.push(_this);
  24427. _this._uid = null;
  24428. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24429. if (BABYLON.PostProcessManager) {
  24430. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24431. }
  24432. if (BABYLON.OutlineRenderer) {
  24433. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24434. }
  24435. if (BABYLON.Tools.IsWindowObjectExist()) {
  24436. _this.attachControl();
  24437. }
  24438. //collision coordinator initialization. For now legacy per default.
  24439. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24440. // Uniform Buffer
  24441. _this._createUbo();
  24442. // Default Image processing definition
  24443. if (BABYLON.ImageProcessingConfiguration) {
  24444. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24445. }
  24446. return _this;
  24447. }
  24448. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24449. /**
  24450. * Texture used in all pbr material as the reflection texture.
  24451. * As in the majority of the scene they are the same (exception for multi room and so on),
  24452. * this is easier to reference from here than from all the materials.
  24453. */
  24454. get: function () {
  24455. return this._environmentTexture;
  24456. },
  24457. /**
  24458. * Texture used in all pbr material as the reflection texture.
  24459. * As in the majority of the scene they are the same (exception for multi room and so on),
  24460. * this is easier to set here than in all the materials.
  24461. */
  24462. set: function (value) {
  24463. if (this._environmentTexture === value) {
  24464. return;
  24465. }
  24466. this._environmentTexture = value;
  24467. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24468. },
  24469. enumerable: true,
  24470. configurable: true
  24471. });
  24472. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24473. /**
  24474. * Default image processing configuration used either in the rendering
  24475. * Forward main pass or through the imageProcessingPostProcess if present.
  24476. * As in the majority of the scene they are the same (exception for multi camera),
  24477. * this is easier to reference from here than from all the materials and post process.
  24478. *
  24479. * No setter as we it is a shared configuration, you can set the values instead.
  24480. */
  24481. get: function () {
  24482. return this._imageProcessingConfiguration;
  24483. },
  24484. enumerable: true,
  24485. configurable: true
  24486. });
  24487. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24488. get: function () {
  24489. return this._forceWireframe;
  24490. },
  24491. /**
  24492. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24493. */
  24494. set: function (value) {
  24495. if (this._forceWireframe === value) {
  24496. return;
  24497. }
  24498. this._forceWireframe = value;
  24499. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24500. },
  24501. enumerable: true,
  24502. configurable: true
  24503. });
  24504. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24505. get: function () {
  24506. return this._forcePointsCloud;
  24507. },
  24508. /**
  24509. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24510. */
  24511. set: function (value) {
  24512. if (this._forcePointsCloud === value) {
  24513. return;
  24514. }
  24515. this._forcePointsCloud = value;
  24516. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24522. /**
  24523. * Gets or sets the animation properties override
  24524. */
  24525. get: function () {
  24526. return this._animationPropertiesOverride;
  24527. },
  24528. set: function (value) {
  24529. this._animationPropertiesOverride = value;
  24530. },
  24531. enumerable: true,
  24532. configurable: true
  24533. });
  24534. Object.defineProperty(Scene.prototype, "onDispose", {
  24535. /** Sets a function to be executed when this scene is disposed. */
  24536. set: function (callback) {
  24537. if (this._onDisposeObserver) {
  24538. this.onDisposeObservable.remove(this._onDisposeObserver);
  24539. }
  24540. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "beforeRender", {
  24546. /** Sets a function to be executed before rendering this scene */
  24547. set: function (callback) {
  24548. if (this._onBeforeRenderObserver) {
  24549. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24550. }
  24551. if (callback) {
  24552. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24553. }
  24554. },
  24555. enumerable: true,
  24556. configurable: true
  24557. });
  24558. Object.defineProperty(Scene.prototype, "afterRender", {
  24559. /** Sets a function to be executed after rendering this scene */
  24560. set: function (callback) {
  24561. if (this._onAfterRenderObserver) {
  24562. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24563. }
  24564. if (callback) {
  24565. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24566. }
  24567. },
  24568. enumerable: true,
  24569. configurable: true
  24570. });
  24571. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24572. /** Sets a function to be executed before rendering a camera*/
  24573. set: function (callback) {
  24574. if (this._onBeforeCameraRenderObserver) {
  24575. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24576. }
  24577. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24578. },
  24579. enumerable: true,
  24580. configurable: true
  24581. });
  24582. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24583. /** Sets a function to be executed after rendering a camera*/
  24584. set: function (callback) {
  24585. if (this._onAfterCameraRenderObserver) {
  24586. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24587. }
  24588. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24594. /**
  24595. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24596. */
  24597. get: function () {
  24598. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24599. },
  24600. enumerable: true,
  24601. configurable: true
  24602. });
  24603. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24604. get: function () {
  24605. return this._useRightHandedSystem;
  24606. },
  24607. /**
  24608. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24609. */
  24610. set: function (value) {
  24611. if (this._useRightHandedSystem === value) {
  24612. return;
  24613. }
  24614. this._useRightHandedSystem = value;
  24615. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24616. },
  24617. enumerable: true,
  24618. configurable: true
  24619. });
  24620. /**
  24621. * Sets the step Id used by deterministic lock step
  24622. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24623. * @param newStepId defines the step Id
  24624. */
  24625. Scene.prototype.setStepId = function (newStepId) {
  24626. this._currentStepId = newStepId;
  24627. };
  24628. ;
  24629. /**
  24630. * Gets the step Id used by deterministic lock step
  24631. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24632. * @returns the step Id
  24633. */
  24634. Scene.prototype.getStepId = function () {
  24635. return this._currentStepId;
  24636. };
  24637. ;
  24638. /**
  24639. * Gets the internal step used by deterministic lock step
  24640. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24641. * @returns the internal step
  24642. */
  24643. Scene.prototype.getInternalStep = function () {
  24644. return this._currentInternalStep;
  24645. };
  24646. ;
  24647. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24648. get: function () {
  24649. return this._fogEnabled;
  24650. },
  24651. /**
  24652. * Gets or sets a boolean indicating if fog is enabled on this scene
  24653. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24654. */
  24655. set: function (value) {
  24656. if (this._fogEnabled === value) {
  24657. return;
  24658. }
  24659. this._fogEnabled = value;
  24660. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. Object.defineProperty(Scene.prototype, "fogMode", {
  24666. get: function () {
  24667. return this._fogMode;
  24668. },
  24669. /**
  24670. * Gets or sets the fog mode to use
  24671. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24672. */
  24673. set: function (value) {
  24674. if (this._fogMode === value) {
  24675. return;
  24676. }
  24677. this._fogMode = value;
  24678. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24684. get: function () {
  24685. return this._shadowsEnabled;
  24686. },
  24687. /**
  24688. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24689. */
  24690. set: function (value) {
  24691. if (this._shadowsEnabled === value) {
  24692. return;
  24693. }
  24694. this._shadowsEnabled = value;
  24695. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24701. get: function () {
  24702. return this._lightsEnabled;
  24703. },
  24704. /**
  24705. * Gets or sets a boolean indicating if lights are enabled on this scene
  24706. */
  24707. set: function (value) {
  24708. if (this._lightsEnabled === value) {
  24709. return;
  24710. }
  24711. this._lightsEnabled = value;
  24712. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24718. /** The default material used on meshes when no material is affected */
  24719. get: function () {
  24720. if (!this._defaultMaterial) {
  24721. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24722. }
  24723. return this._defaultMaterial;
  24724. },
  24725. /** The default material used on meshes when no material is affected */
  24726. set: function (value) {
  24727. this._defaultMaterial = value;
  24728. },
  24729. enumerable: true,
  24730. configurable: true
  24731. });
  24732. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24733. get: function () {
  24734. return this._texturesEnabled;
  24735. },
  24736. /**
  24737. * Gets or sets a boolean indicating if textures are enabled on this scene
  24738. */
  24739. set: function (value) {
  24740. if (this._texturesEnabled === value) {
  24741. return;
  24742. }
  24743. this._texturesEnabled = value;
  24744. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24750. get: function () {
  24751. return this._skeletonsEnabled;
  24752. },
  24753. /**
  24754. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24755. */
  24756. set: function (value) {
  24757. if (this._skeletonsEnabled === value) {
  24758. return;
  24759. }
  24760. this._skeletonsEnabled = value;
  24761. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24762. },
  24763. enumerable: true,
  24764. configurable: true
  24765. });
  24766. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24767. /**
  24768. * Gets the main soundtrack associated with the scene
  24769. */
  24770. get: function () {
  24771. if (!this._mainSoundTrack) {
  24772. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24773. }
  24774. return this._mainSoundTrack;
  24775. },
  24776. enumerable: true,
  24777. configurable: true
  24778. });
  24779. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24780. /** @hidden */
  24781. get: function () {
  24782. return this._alternateRendering;
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24788. /**
  24789. * Gets the list of frustum planes (built from the active camera)
  24790. */
  24791. get: function () {
  24792. return this._frustumPlanes;
  24793. },
  24794. enumerable: true,
  24795. configurable: true
  24796. });
  24797. /**
  24798. * Registers the transient components if needed.
  24799. */
  24800. Scene.prototype._registerTransientComponents = function () {
  24801. // Register components that have been associated lately to the scene.
  24802. if (this._transientComponents.length > 0) {
  24803. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24804. var component = _a[_i];
  24805. component.register();
  24806. }
  24807. this._transientComponents = [];
  24808. }
  24809. };
  24810. /**
  24811. * @hidden
  24812. * Add a component to the scene.
  24813. * Note that the ccomponent could be registered on th next frame if this is called after
  24814. * the register component stage.
  24815. * @param component Defines the component to add to the scene
  24816. */
  24817. Scene.prototype._addComponent = function (component) {
  24818. this._components.push(component);
  24819. this._transientComponents.push(component);
  24820. var serializableComponent = component;
  24821. if (serializableComponent.addFromContainer) {
  24822. this._serializableComponents.push(serializableComponent);
  24823. }
  24824. };
  24825. /**
  24826. * @hidden
  24827. * Gets a component from the scene.
  24828. * @param name defines the name of the component to retrieve
  24829. * @returns the component or null if not present
  24830. */
  24831. Scene.prototype._getComponent = function (name) {
  24832. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24833. var component = _a[_i];
  24834. if (component.name === name) {
  24835. return component;
  24836. }
  24837. }
  24838. return null;
  24839. };
  24840. Object.defineProperty(Scene.prototype, "debugLayer", {
  24841. /**
  24842. * Gets the debug layer (aka Inspector) associated with the scene
  24843. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24844. */
  24845. get: function () {
  24846. if (!this._debugLayer) {
  24847. this._debugLayer = new BABYLON.DebugLayer(this);
  24848. }
  24849. return this._debugLayer;
  24850. },
  24851. enumerable: true,
  24852. configurable: true
  24853. });
  24854. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24855. /**
  24856. * Gets a boolean indicating if collisions are processed on a web worker
  24857. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24858. */
  24859. get: function () {
  24860. return this._workerCollisions;
  24861. },
  24862. set: function (enabled) {
  24863. if (!BABYLON.CollisionCoordinatorLegacy) {
  24864. return;
  24865. }
  24866. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24867. this._workerCollisions = enabled;
  24868. if (this.collisionCoordinator) {
  24869. this.collisionCoordinator.destroy();
  24870. }
  24871. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24872. this.collisionCoordinator.init(this);
  24873. },
  24874. enumerable: true,
  24875. configurable: true
  24876. });
  24877. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24878. /**
  24879. * Gets the octree used to boost mesh selection (picking)
  24880. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24881. */
  24882. get: function () {
  24883. return this._selectionOctree;
  24884. },
  24885. enumerable: true,
  24886. configurable: true
  24887. });
  24888. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24889. /**
  24890. * Gets the mesh that is currently under the pointer
  24891. */
  24892. get: function () {
  24893. return this._pointerOverMesh;
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Scene.prototype, "pointerX", {
  24899. /**
  24900. * Gets the current on-screen X position of the pointer
  24901. */
  24902. get: function () {
  24903. return this._pointerX;
  24904. },
  24905. enumerable: true,
  24906. configurable: true
  24907. });
  24908. Object.defineProperty(Scene.prototype, "pointerY", {
  24909. /**
  24910. * Gets the current on-screen Y position of the pointer
  24911. */
  24912. get: function () {
  24913. return this._pointerY;
  24914. },
  24915. enumerable: true,
  24916. configurable: true
  24917. });
  24918. /**
  24919. * Gets the cached material (ie. the latest rendered one)
  24920. * @returns the cached material
  24921. */
  24922. Scene.prototype.getCachedMaterial = function () {
  24923. return this._cachedMaterial;
  24924. };
  24925. /**
  24926. * Gets the cached effect (ie. the latest rendered one)
  24927. * @returns the cached effect
  24928. */
  24929. Scene.prototype.getCachedEffect = function () {
  24930. return this._cachedEffect;
  24931. };
  24932. /**
  24933. * Gets the cached visibility state (ie. the latest rendered one)
  24934. * @returns the cached visibility state
  24935. */
  24936. Scene.prototype.getCachedVisibility = function () {
  24937. return this._cachedVisibility;
  24938. };
  24939. /**
  24940. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24941. * @param material defines the current material
  24942. * @param effect defines the current effect
  24943. * @param visibility defines the current visibility state
  24944. * @returns true if one parameter is not cached
  24945. */
  24946. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24947. if (visibility === void 0) { visibility = 1; }
  24948. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24949. };
  24950. /**
  24951. * Gets the outline renderer associated with the scene
  24952. * @returns a OutlineRenderer
  24953. */
  24954. Scene.prototype.getOutlineRenderer = function () {
  24955. return this._outlineRenderer;
  24956. };
  24957. /**
  24958. * Gets the engine associated with the scene
  24959. * @returns an Engine
  24960. */
  24961. Scene.prototype.getEngine = function () {
  24962. return this._engine;
  24963. };
  24964. /**
  24965. * Gets the total number of vertices rendered per frame
  24966. * @returns the total number of vertices rendered per frame
  24967. */
  24968. Scene.prototype.getTotalVertices = function () {
  24969. return this._totalVertices.current;
  24970. };
  24971. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24972. /**
  24973. * Gets the performance counter for total vertices
  24974. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24975. */
  24976. get: function () {
  24977. return this._totalVertices;
  24978. },
  24979. enumerable: true,
  24980. configurable: true
  24981. });
  24982. /**
  24983. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24984. * @returns the total number of active indices rendered per frame
  24985. */
  24986. Scene.prototype.getActiveIndices = function () {
  24987. return this._activeIndices.current;
  24988. };
  24989. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24990. /**
  24991. * Gets the performance counter for active indices
  24992. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24993. */
  24994. get: function () {
  24995. return this._activeIndices;
  24996. },
  24997. enumerable: true,
  24998. configurable: true
  24999. });
  25000. /**
  25001. * Gets the total number of active particles rendered per frame
  25002. * @returns the total number of active particles rendered per frame
  25003. */
  25004. Scene.prototype.getActiveParticles = function () {
  25005. return this._activeParticles.current;
  25006. };
  25007. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25008. /**
  25009. * Gets the performance counter for active particles
  25010. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25011. */
  25012. get: function () {
  25013. return this._activeParticles;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. /**
  25019. * Gets the total number of active bones rendered per frame
  25020. * @returns the total number of active bones rendered per frame
  25021. */
  25022. Scene.prototype.getActiveBones = function () {
  25023. return this._activeBones.current;
  25024. };
  25025. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25026. /**
  25027. * Gets the performance counter for active bones
  25028. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25029. */
  25030. get: function () {
  25031. return this._activeBones;
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. /** @hidden */
  25037. Scene.prototype.getInterFramePerfCounter = function () {
  25038. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25039. return 0;
  25040. };
  25041. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25042. /** @hidden */
  25043. get: function () {
  25044. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25045. return null;
  25046. },
  25047. enumerable: true,
  25048. configurable: true
  25049. });
  25050. /** @hidden */
  25051. Scene.prototype.getLastFrameDuration = function () {
  25052. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25053. return 0;
  25054. };
  25055. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25056. /** @hidden */
  25057. get: function () {
  25058. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25059. return null;
  25060. },
  25061. enumerable: true,
  25062. configurable: true
  25063. });
  25064. /** @hidden */
  25065. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25066. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25067. return 0;
  25068. };
  25069. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25070. /** @hidden */
  25071. get: function () {
  25072. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25073. return null;
  25074. },
  25075. enumerable: true,
  25076. configurable: true
  25077. });
  25078. /**
  25079. * Gets the array of active meshes
  25080. * @returns an array of AbstractMesh
  25081. */
  25082. Scene.prototype.getActiveMeshes = function () {
  25083. return this._activeMeshes;
  25084. };
  25085. /** @hidden */
  25086. Scene.prototype.getRenderTargetsDuration = function () {
  25087. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25088. return 0;
  25089. };
  25090. /** @hidden */
  25091. Scene.prototype.getRenderDuration = function () {
  25092. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25093. return 0;
  25094. };
  25095. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25096. /** @hidden */
  25097. get: function () {
  25098. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25099. return null;
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. /** @hidden */
  25105. Scene.prototype.getParticlesDuration = function () {
  25106. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25107. return 0;
  25108. };
  25109. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25110. /** @hidden */
  25111. get: function () {
  25112. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25113. return null;
  25114. },
  25115. enumerable: true,
  25116. configurable: true
  25117. });
  25118. /** @hidden */
  25119. Scene.prototype.getSpritesDuration = function () {
  25120. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25121. return 0;
  25122. };
  25123. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25124. /** @hidden */
  25125. get: function () {
  25126. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25127. return null;
  25128. },
  25129. enumerable: true,
  25130. configurable: true
  25131. });
  25132. /**
  25133. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25134. * @returns a number
  25135. */
  25136. Scene.prototype.getAnimationRatio = function () {
  25137. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25138. };
  25139. /**
  25140. * Gets an unique Id for the current frame
  25141. * @returns a number
  25142. */
  25143. Scene.prototype.getRenderId = function () {
  25144. return this._renderId;
  25145. };
  25146. /** Call this function if you want to manually increment the render Id*/
  25147. Scene.prototype.incrementRenderId = function () {
  25148. this._renderId++;
  25149. };
  25150. Scene.prototype._updatePointerPosition = function (evt) {
  25151. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25152. if (!canvasRect) {
  25153. return;
  25154. }
  25155. this._pointerX = evt.clientX - canvasRect.left;
  25156. this._pointerY = evt.clientY - canvasRect.top;
  25157. this._unTranslatedPointerX = this._pointerX;
  25158. this._unTranslatedPointerY = this._pointerY;
  25159. };
  25160. Scene.prototype._createUbo = function () {
  25161. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25162. this._sceneUbo.addUniform("viewProjection", 16);
  25163. this._sceneUbo.addUniform("view", 16);
  25164. };
  25165. Scene.prototype._createAlternateUbo = function () {
  25166. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25167. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25168. this._alternateSceneUbo.addUniform("view", 16);
  25169. };
  25170. // Pointers handling
  25171. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25172. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25173. if (result) {
  25174. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25175. }
  25176. return result;
  25177. };
  25178. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25179. if (pointerInfo.pickInfo) {
  25180. if (!pointerInfo.pickInfo.ray) {
  25181. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25182. }
  25183. }
  25184. };
  25185. /**
  25186. * Use this method to simulate a pointer move on a mesh
  25187. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25188. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25189. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25190. * @returns the current scene
  25191. */
  25192. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25193. var evt = new PointerEvent("pointermove", pointerEventInit);
  25194. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25195. return this;
  25196. }
  25197. return this._processPointerMove(pickResult, evt);
  25198. };
  25199. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25200. var canvas = this._engine.getRenderingCanvas();
  25201. if (!canvas) {
  25202. return this;
  25203. }
  25204. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25205. this.setPointerOverSprite(null);
  25206. this.setPointerOverMesh(pickResult.pickedMesh);
  25207. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25208. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25209. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25210. }
  25211. else {
  25212. canvas.style.cursor = this.hoverCursor;
  25213. }
  25214. }
  25215. else {
  25216. canvas.style.cursor = this.defaultCursor;
  25217. }
  25218. }
  25219. else {
  25220. this.setPointerOverMesh(null);
  25221. // Sprites
  25222. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25223. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25224. this.setPointerOverSprite(pickResult.pickedSprite);
  25225. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25226. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25227. }
  25228. else {
  25229. canvas.style.cursor = this.hoverCursor;
  25230. }
  25231. }
  25232. else {
  25233. this.setPointerOverSprite(null);
  25234. // Restore pointer
  25235. canvas.style.cursor = this.defaultCursor;
  25236. }
  25237. }
  25238. if (pickResult) {
  25239. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25240. if (this.onPointerMove) {
  25241. this.onPointerMove(evt, pickResult, type);
  25242. }
  25243. if (this.onPointerObservable.hasObservers()) {
  25244. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25245. this._setRayOnPointerInfo(pi);
  25246. this.onPointerObservable.notifyObservers(pi, type);
  25247. }
  25248. }
  25249. return this;
  25250. };
  25251. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25252. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25253. if (pickResult) {
  25254. pi.ray = pickResult.ray;
  25255. }
  25256. this.onPrePointerObservable.notifyObservers(pi, type);
  25257. if (pi.skipOnPointerObservable) {
  25258. return true;
  25259. }
  25260. else {
  25261. return false;
  25262. }
  25263. };
  25264. /**
  25265. * Use this method to simulate a pointer down on a mesh
  25266. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25267. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25268. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25269. * @returns the current scene
  25270. */
  25271. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25272. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25273. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25274. return this;
  25275. }
  25276. return this._processPointerDown(pickResult, evt);
  25277. };
  25278. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25279. var _this = this;
  25280. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25281. this._pickedDownMesh = pickResult.pickedMesh;
  25282. var actionManager = pickResult.pickedMesh.actionManager;
  25283. if (actionManager) {
  25284. if (actionManager.hasPickTriggers) {
  25285. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25286. switch (evt.button) {
  25287. case 0:
  25288. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25289. break;
  25290. case 1:
  25291. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25292. break;
  25293. case 2:
  25294. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25295. break;
  25296. }
  25297. }
  25298. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25299. window.setTimeout(function () {
  25300. 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);
  25301. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25302. if (_this._totalPointersPressed !== 0 &&
  25303. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25304. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25305. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25306. _this._startingPointerTime = 0;
  25307. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25308. }
  25309. }
  25310. }, Scene.LongPressDelay);
  25311. }
  25312. }
  25313. }
  25314. if (pickResult) {
  25315. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25316. if (this.onPointerDown) {
  25317. this.onPointerDown(evt, pickResult, type);
  25318. }
  25319. if (this.onPointerObservable.hasObservers()) {
  25320. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25321. this._setRayOnPointerInfo(pi);
  25322. this.onPointerObservable.notifyObservers(pi, type);
  25323. }
  25324. }
  25325. return this;
  25326. };
  25327. /**
  25328. * Use this method to simulate a pointer up on a mesh
  25329. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25330. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25331. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25332. * @returns the current scene
  25333. */
  25334. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25335. var evt = new PointerEvent("pointerup", pointerEventInit);
  25336. var clickInfo = new ClickInfo();
  25337. clickInfo.singleClick = true;
  25338. clickInfo.ignore = true;
  25339. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25340. return this;
  25341. }
  25342. return this._processPointerUp(pickResult, evt, clickInfo);
  25343. };
  25344. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25345. if (pickResult && pickResult && pickResult.pickedMesh) {
  25346. this._pickedUpMesh = pickResult.pickedMesh;
  25347. if (this._pickedDownMesh === this._pickedUpMesh) {
  25348. if (this.onPointerPick) {
  25349. this.onPointerPick(evt, pickResult);
  25350. }
  25351. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25352. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25353. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25354. this._setRayOnPointerInfo(pi);
  25355. this.onPointerObservable.notifyObservers(pi, type_1);
  25356. }
  25357. }
  25358. if (pickResult.pickedMesh.actionManager) {
  25359. if (clickInfo.ignore) {
  25360. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25361. }
  25362. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25363. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25364. }
  25365. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25366. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25367. }
  25368. }
  25369. }
  25370. if (this._pickedDownMesh &&
  25371. this._pickedDownMesh.actionManager &&
  25372. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25373. this._pickedDownMesh !== this._pickedUpMesh) {
  25374. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25375. }
  25376. var type = BABYLON.PointerEventTypes.POINTERUP;
  25377. if (this.onPointerObservable.hasObservers()) {
  25378. if (!clickInfo.ignore) {
  25379. if (!clickInfo.hasSwiped) {
  25380. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25381. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25382. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25383. this._setRayOnPointerInfo(pi);
  25384. this.onPointerObservable.notifyObservers(pi, type_2);
  25385. }
  25386. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25387. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25388. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25389. this._setRayOnPointerInfo(pi);
  25390. this.onPointerObservable.notifyObservers(pi, type_3);
  25391. }
  25392. }
  25393. }
  25394. else {
  25395. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25396. this._setRayOnPointerInfo(pi);
  25397. this.onPointerObservable.notifyObservers(pi, type);
  25398. }
  25399. }
  25400. if (this.onPointerUp) {
  25401. this.onPointerUp(evt, pickResult, type);
  25402. }
  25403. return this;
  25404. };
  25405. /**
  25406. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25407. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25408. * @returns true if the pointer was captured
  25409. */
  25410. Scene.prototype.isPointerCaptured = function (pointerId) {
  25411. if (pointerId === void 0) { pointerId = 0; }
  25412. return this._pointerCaptures[pointerId];
  25413. };
  25414. /**
  25415. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25416. * @param attachUp defines if you want to attach events to pointerup
  25417. * @param attachDown defines if you want to attach events to pointerdown
  25418. * @param attachMove defines if you want to attach events to pointermove
  25419. */
  25420. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25421. var _this = this;
  25422. if (attachUp === void 0) { attachUp = true; }
  25423. if (attachDown === void 0) { attachDown = true; }
  25424. if (attachMove === void 0) { attachMove = true; }
  25425. this._initActionManager = function (act, clickInfo) {
  25426. if (!_this._meshPickProceed) {
  25427. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25428. _this._currentPickResult = pickResult;
  25429. if (pickResult) {
  25430. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25431. }
  25432. _this._meshPickProceed = true;
  25433. }
  25434. return act;
  25435. };
  25436. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25437. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25438. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25439. btn !== _this._previousButtonPressed) {
  25440. _this._doubleClickOccured = false;
  25441. clickInfo.singleClick = true;
  25442. clickInfo.ignore = false;
  25443. cb(clickInfo, _this._currentPickResult);
  25444. }
  25445. };
  25446. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25447. var clickInfo = new ClickInfo();
  25448. _this._currentPickResult = null;
  25449. var act = null;
  25450. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25451. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25452. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25453. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25454. act = _this._initActionManager(act, clickInfo);
  25455. if (act)
  25456. checkPicking = act.hasPickTriggers;
  25457. }
  25458. if (checkPicking) {
  25459. var btn = evt.button;
  25460. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25461. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25462. if (!clickInfo.hasSwiped) {
  25463. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25464. if (!checkSingleClickImmediately) {
  25465. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25466. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25467. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25468. act = _this._initActionManager(act, clickInfo);
  25469. if (act)
  25470. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25471. }
  25472. }
  25473. if (checkSingleClickImmediately) {
  25474. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25475. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25476. btn !== _this._previousButtonPressed) {
  25477. clickInfo.singleClick = true;
  25478. cb(clickInfo, _this._currentPickResult);
  25479. }
  25480. }
  25481. // at least one double click is required to be check and exclusive double click is enabled
  25482. else {
  25483. // wait that no double click has been raised during the double click delay
  25484. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25485. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25486. }
  25487. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25488. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25489. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25490. act = _this._initActionManager(act, clickInfo);
  25491. if (act)
  25492. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25493. }
  25494. if (checkDoubleClick) {
  25495. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25496. if (btn === _this._previousButtonPressed &&
  25497. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25498. !_this._doubleClickOccured) {
  25499. // pointer has not moved for 2 clicks, it's a double click
  25500. if (!clickInfo.hasSwiped &&
  25501. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25502. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25503. _this._previousStartingPointerTime = 0;
  25504. _this._doubleClickOccured = true;
  25505. clickInfo.doubleClick = true;
  25506. clickInfo.ignore = false;
  25507. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25508. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25509. }
  25510. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25511. cb(clickInfo, _this._currentPickResult);
  25512. }
  25513. // if the two successive clicks are too far, it's just two simple clicks
  25514. else {
  25515. _this._doubleClickOccured = false;
  25516. _this._previousStartingPointerTime = _this._startingPointerTime;
  25517. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25518. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25519. _this._previousButtonPressed = btn;
  25520. if (Scene.ExclusiveDoubleClickMode) {
  25521. if (_this._previousDelayedSimpleClickTimeout) {
  25522. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25523. }
  25524. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25525. cb(clickInfo, _this._previousPickResult);
  25526. }
  25527. else {
  25528. cb(clickInfo, _this._currentPickResult);
  25529. }
  25530. }
  25531. }
  25532. // just the first click of the double has been raised
  25533. else {
  25534. _this._doubleClickOccured = false;
  25535. _this._previousStartingPointerTime = _this._startingPointerTime;
  25536. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25537. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25538. _this._previousButtonPressed = btn;
  25539. }
  25540. }
  25541. }
  25542. }
  25543. clickInfo.ignore = true;
  25544. cb(clickInfo, _this._currentPickResult);
  25545. };
  25546. this._spritePredicate = function (sprite) {
  25547. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25548. };
  25549. this._onPointerMove = function (evt) {
  25550. _this._updatePointerPosition(evt);
  25551. // PreObservable support
  25552. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25553. return;
  25554. }
  25555. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25556. return;
  25557. }
  25558. if (!_this.pointerMovePredicate) {
  25559. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25560. }
  25561. // Meshes
  25562. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25563. _this._processPointerMove(pickResult, evt);
  25564. };
  25565. this._onPointerDown = function (evt) {
  25566. _this._totalPointersPressed++;
  25567. _this._pickedDownMesh = null;
  25568. _this._meshPickProceed = false;
  25569. _this._updatePointerPosition(evt);
  25570. if (_this.preventDefaultOnPointerDown && canvas) {
  25571. evt.preventDefault();
  25572. canvas.focus();
  25573. }
  25574. // PreObservable support
  25575. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25576. return;
  25577. }
  25578. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25579. return;
  25580. }
  25581. _this._pointerCaptures[evt.pointerId] = true;
  25582. _this._startingPointerPosition.x = _this._pointerX;
  25583. _this._startingPointerPosition.y = _this._pointerY;
  25584. _this._startingPointerTime = Date.now();
  25585. if (!_this.pointerDownPredicate) {
  25586. _this.pointerDownPredicate = function (mesh) {
  25587. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25588. };
  25589. }
  25590. // Meshes
  25591. _this._pickedDownMesh = null;
  25592. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25593. _this._processPointerDown(pickResult, evt);
  25594. // Sprites
  25595. _this._pickedDownSprite = null;
  25596. if (_this.spriteManagers.length > 0) {
  25597. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25598. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25599. if (pickResult.pickedSprite.actionManager) {
  25600. _this._pickedDownSprite = pickResult.pickedSprite;
  25601. switch (evt.button) {
  25602. case 0:
  25603. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25604. break;
  25605. case 1:
  25606. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25607. break;
  25608. case 2:
  25609. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25610. break;
  25611. }
  25612. if (pickResult.pickedSprite.actionManager) {
  25613. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25614. }
  25615. }
  25616. }
  25617. }
  25618. };
  25619. this._onPointerUp = function (evt) {
  25620. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25621. return; // So we need to test it the pointer down was pressed before.
  25622. }
  25623. _this._totalPointersPressed--;
  25624. _this._pickedUpMesh = null;
  25625. _this._meshPickProceed = false;
  25626. _this._updatePointerPosition(evt);
  25627. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25628. // PreObservable support
  25629. if (_this.onPrePointerObservable.hasObservers()) {
  25630. if (!clickInfo.ignore) {
  25631. if (!clickInfo.hasSwiped) {
  25632. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25633. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25634. return;
  25635. }
  25636. }
  25637. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25638. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25639. return;
  25640. }
  25641. }
  25642. }
  25643. }
  25644. else {
  25645. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25646. return;
  25647. }
  25648. }
  25649. }
  25650. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25651. return;
  25652. }
  25653. _this._pointerCaptures[evt.pointerId] = false;
  25654. if (!_this.pointerUpPredicate) {
  25655. _this.pointerUpPredicate = function (mesh) {
  25656. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25657. };
  25658. }
  25659. // Meshes
  25660. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25661. _this._initActionManager(null, clickInfo);
  25662. }
  25663. if (!pickResult) {
  25664. pickResult = _this._currentPickResult;
  25665. }
  25666. _this._processPointerUp(pickResult, evt, clickInfo);
  25667. // Sprites
  25668. if (!clickInfo.ignore) {
  25669. if (_this.spriteManagers.length > 0) {
  25670. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25671. if (spritePickResult) {
  25672. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25673. if (spritePickResult.pickedSprite.actionManager) {
  25674. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25675. if (spritePickResult.pickedSprite.actionManager) {
  25676. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25677. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25678. }
  25679. }
  25680. }
  25681. }
  25682. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25683. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25684. }
  25685. }
  25686. }
  25687. }
  25688. _this._previousPickResult = _this._currentPickResult;
  25689. });
  25690. };
  25691. this._onKeyDown = function (evt) {
  25692. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25693. if (_this.onPreKeyboardObservable.hasObservers()) {
  25694. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25695. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25696. if (pi.skipOnPointerObservable) {
  25697. return;
  25698. }
  25699. }
  25700. if (_this.onKeyboardObservable.hasObservers()) {
  25701. var pi = new BABYLON.KeyboardInfo(type, evt);
  25702. _this.onKeyboardObservable.notifyObservers(pi, type);
  25703. }
  25704. if (_this.actionManager) {
  25705. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25706. }
  25707. };
  25708. this._onKeyUp = function (evt) {
  25709. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25710. if (_this.onPreKeyboardObservable.hasObservers()) {
  25711. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25712. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25713. if (pi.skipOnPointerObservable) {
  25714. return;
  25715. }
  25716. }
  25717. if (_this.onKeyboardObservable.hasObservers()) {
  25718. var pi = new BABYLON.KeyboardInfo(type, evt);
  25719. _this.onKeyboardObservable.notifyObservers(pi, type);
  25720. }
  25721. if (_this.actionManager) {
  25722. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25723. }
  25724. };
  25725. var engine = this.getEngine();
  25726. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25727. if (!canvas) {
  25728. return;
  25729. }
  25730. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25731. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25732. });
  25733. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25734. if (!canvas) {
  25735. return;
  25736. }
  25737. canvas.removeEventListener("keydown", _this._onKeyDown);
  25738. canvas.removeEventListener("keyup", _this._onKeyUp);
  25739. });
  25740. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25741. var canvas = this._engine.getRenderingCanvas();
  25742. if (!canvas) {
  25743. return;
  25744. }
  25745. if (attachMove) {
  25746. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25747. // Wheel
  25748. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25749. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25750. }
  25751. if (attachDown) {
  25752. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25753. }
  25754. if (attachUp) {
  25755. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25756. }
  25757. canvas.tabIndex = 1;
  25758. };
  25759. /** Detaches all event handlers*/
  25760. Scene.prototype.detachControl = function () {
  25761. var engine = this.getEngine();
  25762. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25763. var canvas = engine.getRenderingCanvas();
  25764. if (!canvas) {
  25765. return;
  25766. }
  25767. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25768. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25769. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25770. if (this._onCanvasBlurObserver) {
  25771. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25772. }
  25773. if (this._onCanvasFocusObserver) {
  25774. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25775. }
  25776. // Wheel
  25777. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25778. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25779. // Keyboard
  25780. canvas.removeEventListener("keydown", this._onKeyDown);
  25781. canvas.removeEventListener("keyup", this._onKeyUp);
  25782. // Observables
  25783. this.onKeyboardObservable.clear();
  25784. this.onPreKeyboardObservable.clear();
  25785. this.onPointerObservable.clear();
  25786. this.onPrePointerObservable.clear();
  25787. };
  25788. /**
  25789. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25790. * Delay loaded resources are not taking in account
  25791. * @return true if all required resources are ready
  25792. */
  25793. Scene.prototype.isReady = function () {
  25794. if (this._isDisposed) {
  25795. return false;
  25796. }
  25797. if (this._pendingData.length > 0) {
  25798. return false;
  25799. }
  25800. var index;
  25801. var engine = this.getEngine();
  25802. // Geometries
  25803. for (index = 0; index < this.geometries.length; index++) {
  25804. var geometry = this.geometries[index];
  25805. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25806. return false;
  25807. }
  25808. }
  25809. // Meshes
  25810. for (index = 0; index < this.meshes.length; index++) {
  25811. var mesh = this.meshes[index];
  25812. if (!mesh.isEnabled()) {
  25813. continue;
  25814. }
  25815. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25816. continue;
  25817. }
  25818. if (!mesh.isReady(true)) {
  25819. return false;
  25820. }
  25821. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25822. // Is Ready For Mesh
  25823. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25824. var step = _a[_i];
  25825. if (!step.action(mesh, hardwareInstancedRendering)) {
  25826. return false;
  25827. }
  25828. }
  25829. }
  25830. // Post-processes
  25831. if (this.activeCameras && this.activeCameras.length > 0) {
  25832. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25833. var camera = _c[_b];
  25834. if (!camera.isReady(true)) {
  25835. return false;
  25836. }
  25837. }
  25838. }
  25839. else if (this.activeCamera) {
  25840. if (!this.activeCamera.isReady(true)) {
  25841. return false;
  25842. }
  25843. }
  25844. // Particles
  25845. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25846. var particleSystem = _e[_d];
  25847. if (!particleSystem.isReady()) {
  25848. return false;
  25849. }
  25850. }
  25851. return true;
  25852. };
  25853. /** Resets all cached information relative to material (including effect and visibility) */
  25854. Scene.prototype.resetCachedMaterial = function () {
  25855. this._cachedMaterial = null;
  25856. this._cachedEffect = null;
  25857. this._cachedVisibility = null;
  25858. };
  25859. /**
  25860. * Registers a function to be called before every frame render
  25861. * @param func defines the function to register
  25862. */
  25863. Scene.prototype.registerBeforeRender = function (func) {
  25864. this.onBeforeRenderObservable.add(func);
  25865. };
  25866. /**
  25867. * Unregisters a function called before every frame render
  25868. * @param func defines the function to unregister
  25869. */
  25870. Scene.prototype.unregisterBeforeRender = function (func) {
  25871. this.onBeforeRenderObservable.removeCallback(func);
  25872. };
  25873. /**
  25874. * Registers a function to be called after every frame render
  25875. * @param func defines the function to register
  25876. */
  25877. Scene.prototype.registerAfterRender = function (func) {
  25878. this.onAfterRenderObservable.add(func);
  25879. };
  25880. /**
  25881. * Unregisters a function called after every frame render
  25882. * @param func defines the function to unregister
  25883. */
  25884. Scene.prototype.unregisterAfterRender = function (func) {
  25885. this.onAfterRenderObservable.removeCallback(func);
  25886. };
  25887. Scene.prototype._executeOnceBeforeRender = function (func) {
  25888. var _this = this;
  25889. var execFunc = function () {
  25890. func();
  25891. setTimeout(function () {
  25892. _this.unregisterBeforeRender(execFunc);
  25893. });
  25894. };
  25895. this.registerBeforeRender(execFunc);
  25896. };
  25897. /**
  25898. * The provided function will run before render once and will be disposed afterwards.
  25899. * A timeout delay can be provided so that the function will be executed in N ms.
  25900. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25901. * @param func The function to be executed.
  25902. * @param timeout optional delay in ms
  25903. */
  25904. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25905. var _this = this;
  25906. if (timeout !== undefined) {
  25907. setTimeout(function () {
  25908. _this._executeOnceBeforeRender(func);
  25909. }, timeout);
  25910. }
  25911. else {
  25912. this._executeOnceBeforeRender(func);
  25913. }
  25914. };
  25915. /** @hidden */
  25916. Scene.prototype._addPendingData = function (data) {
  25917. this._pendingData.push(data);
  25918. };
  25919. /** @hidden */
  25920. Scene.prototype._removePendingData = function (data) {
  25921. var wasLoading = this.isLoading;
  25922. var index = this._pendingData.indexOf(data);
  25923. if (index !== -1) {
  25924. this._pendingData.splice(index, 1);
  25925. }
  25926. if (wasLoading && !this.isLoading) {
  25927. this.onDataLoadedObservable.notifyObservers(this);
  25928. }
  25929. };
  25930. /**
  25931. * Returns the number of items waiting to be loaded
  25932. * @returns the number of items waiting to be loaded
  25933. */
  25934. Scene.prototype.getWaitingItemsCount = function () {
  25935. return this._pendingData.length;
  25936. };
  25937. Object.defineProperty(Scene.prototype, "isLoading", {
  25938. /**
  25939. * Returns a boolean indicating if the scene is still loading data
  25940. */
  25941. get: function () {
  25942. return this._pendingData.length > 0;
  25943. },
  25944. enumerable: true,
  25945. configurable: true
  25946. });
  25947. /**
  25948. * Registers a function to be executed when the scene is ready
  25949. * @param {Function} func - the function to be executed
  25950. */
  25951. Scene.prototype.executeWhenReady = function (func) {
  25952. var _this = this;
  25953. this.onReadyObservable.add(func);
  25954. if (this._executeWhenReadyTimeoutId !== -1) {
  25955. return;
  25956. }
  25957. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25958. _this._checkIsReady();
  25959. }, 150);
  25960. };
  25961. /**
  25962. * Returns a promise that resolves when the scene is ready
  25963. * @returns A promise that resolves when the scene is ready
  25964. */
  25965. Scene.prototype.whenReadyAsync = function () {
  25966. var _this = this;
  25967. return new Promise(function (resolve) {
  25968. _this.executeWhenReady(function () {
  25969. resolve();
  25970. });
  25971. });
  25972. };
  25973. /** @hidden */
  25974. Scene.prototype._checkIsReady = function () {
  25975. var _this = this;
  25976. this._registerTransientComponents();
  25977. if (this.isReady()) {
  25978. this.onReadyObservable.notifyObservers(this);
  25979. this.onReadyObservable.clear();
  25980. this._executeWhenReadyTimeoutId = -1;
  25981. return;
  25982. }
  25983. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25984. _this._checkIsReady();
  25985. }, 150);
  25986. };
  25987. // Animations
  25988. /**
  25989. * Will start the animation sequence of a given target
  25990. * @param target defines the target
  25991. * @param from defines from which frame should animation start
  25992. * @param to defines until which frame should animation run.
  25993. * @param weight defines the weight to apply to the animation (1.0 by default)
  25994. * @param loop defines if the animation loops
  25995. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25996. * @param onAnimationEnd defines the function to be executed when the animation ends
  25997. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25998. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25999. * @returns the animatable object created for this animation
  26000. */
  26001. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26002. if (weight === void 0) { weight = 1.0; }
  26003. if (speedRatio === void 0) { speedRatio = 1.0; }
  26004. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26005. returnedAnimatable.weight = weight;
  26006. return returnedAnimatable;
  26007. };
  26008. /**
  26009. * Will start the animation sequence of a given target
  26010. * @param target defines the target
  26011. * @param from defines from which frame should animation start
  26012. * @param to defines until which frame should animation run.
  26013. * @param loop defines if the animation loops
  26014. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26015. * @param onAnimationEnd defines the function to be executed when the animation ends
  26016. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26017. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26018. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26019. * @returns the animatable object created for this animation
  26020. */
  26021. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26022. if (speedRatio === void 0) { speedRatio = 1.0; }
  26023. if (stopCurrent === void 0) { stopCurrent = true; }
  26024. if (from > to && speedRatio > 0) {
  26025. speedRatio *= -1;
  26026. }
  26027. if (stopCurrent) {
  26028. this.stopAnimation(target, undefined, targetMask);
  26029. }
  26030. if (!animatable) {
  26031. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26032. }
  26033. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26034. // Local animations
  26035. if (target.animations && shouldRunTargetAnimations) {
  26036. animatable.appendAnimations(target, target.animations);
  26037. }
  26038. // Children animations
  26039. if (target.getAnimatables) {
  26040. var animatables = target.getAnimatables();
  26041. for (var index = 0; index < animatables.length; index++) {
  26042. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26043. }
  26044. }
  26045. animatable.reset();
  26046. return animatable;
  26047. };
  26048. /**
  26049. * Begin a new animation on a given node
  26050. * @param target defines the target where the animation will take place
  26051. * @param animations defines the list of animations to start
  26052. * @param from defines the initial value
  26053. * @param to defines the final value
  26054. * @param loop defines if you want animation to loop (off by default)
  26055. * @param speedRatio defines the speed ratio to apply to all animations
  26056. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26057. * @returns the list of created animatables
  26058. */
  26059. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26060. if (speedRatio === undefined) {
  26061. speedRatio = 1.0;
  26062. }
  26063. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26064. return animatable;
  26065. };
  26066. /**
  26067. * Begin a new animation on a given node and its hierarchy
  26068. * @param target defines the root node where the animation will take place
  26069. * @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.
  26070. * @param animations defines the list of animations to start
  26071. * @param from defines the initial value
  26072. * @param to defines the final value
  26073. * @param loop defines if you want animation to loop (off by default)
  26074. * @param speedRatio defines the speed ratio to apply to all animations
  26075. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26076. * @returns the list of animatables created for all nodes
  26077. */
  26078. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26079. var children = target.getDescendants(directDescendantsOnly);
  26080. var result = [];
  26081. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26082. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26083. var child = children_1[_i];
  26084. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26085. }
  26086. return result;
  26087. };
  26088. /**
  26089. * Gets the animatable associated with a specific target
  26090. * @param target defines the target of the animatable
  26091. * @returns the required animatable if found
  26092. */
  26093. Scene.prototype.getAnimatableByTarget = function (target) {
  26094. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26095. if (this._activeAnimatables[index].target === target) {
  26096. return this._activeAnimatables[index];
  26097. }
  26098. }
  26099. return null;
  26100. };
  26101. /**
  26102. * Gets all animatables associated with a given target
  26103. * @param target defines the target to look animatables for
  26104. * @returns an array of Animatables
  26105. */
  26106. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26107. var result = [];
  26108. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26109. if (this._activeAnimatables[index].target === target) {
  26110. result.push(this._activeAnimatables[index]);
  26111. }
  26112. }
  26113. return result;
  26114. };
  26115. Object.defineProperty(Scene.prototype, "animatables", {
  26116. /**
  26117. * Gets all animatable attached to the scene
  26118. */
  26119. get: function () {
  26120. return this._activeAnimatables;
  26121. },
  26122. enumerable: true,
  26123. configurable: true
  26124. });
  26125. /**
  26126. * Will stop the animation of the given target
  26127. * @param target - the target
  26128. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26129. * @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)
  26130. */
  26131. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26132. var animatables = this.getAllAnimatablesByTarget(target);
  26133. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26134. var animatable = animatables_1[_i];
  26135. animatable.stop(animationName, targetMask);
  26136. }
  26137. };
  26138. /**
  26139. * Stops and removes all animations that have been applied to the scene
  26140. */
  26141. Scene.prototype.stopAllAnimations = function () {
  26142. if (this._activeAnimatables) {
  26143. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26144. this._activeAnimatables[i].stop();
  26145. }
  26146. this._activeAnimatables = [];
  26147. }
  26148. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26149. var group = _a[_i];
  26150. group.stop();
  26151. }
  26152. };
  26153. Scene.prototype._animate = function () {
  26154. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26155. return;
  26156. }
  26157. // Getting time
  26158. var now = BABYLON.Tools.Now;
  26159. if (!this._animationTimeLast) {
  26160. if (this._pendingData.length > 0) {
  26161. return;
  26162. }
  26163. this._animationTimeLast = now;
  26164. }
  26165. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26166. this._animationTime += deltaTime;
  26167. this._animationTimeLast = now;
  26168. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26169. this._activeAnimatables[index]._animate(this._animationTime);
  26170. }
  26171. // Late animation bindings
  26172. this._processLateAnimationBindings();
  26173. };
  26174. /** @hidden */
  26175. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26176. var target = runtimeAnimation.target;
  26177. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26178. if (!target._lateAnimationHolders) {
  26179. target._lateAnimationHolders = {};
  26180. }
  26181. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26182. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26183. totalWeight: 0,
  26184. animations: [],
  26185. originalValue: originalValue
  26186. };
  26187. }
  26188. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26189. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26190. };
  26191. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26192. var normalizer = 1.0;
  26193. var finalPosition = BABYLON.Tmp.Vector3[0];
  26194. var finalScaling = BABYLON.Tmp.Vector3[1];
  26195. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26196. var startIndex = 0;
  26197. var originalAnimation = holder.animations[0];
  26198. var originalValue = holder.originalValue;
  26199. var scale = 1;
  26200. if (holder.totalWeight < 1.0) {
  26201. // We need to mix the original value in
  26202. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26203. scale = 1.0 - holder.totalWeight;
  26204. }
  26205. else {
  26206. startIndex = 1;
  26207. // We need to normalize the weights
  26208. normalizer = holder.totalWeight;
  26209. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26210. scale = originalAnimation.weight / normalizer;
  26211. if (scale == 1) {
  26212. return originalAnimation.currentValue;
  26213. }
  26214. }
  26215. finalScaling.scaleInPlace(scale);
  26216. finalPosition.scaleInPlace(scale);
  26217. finalQuaternion.scaleInPlace(scale);
  26218. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26219. var runtimeAnimation = holder.animations[animIndex];
  26220. var scale = runtimeAnimation.weight / normalizer;
  26221. var currentPosition = BABYLON.Tmp.Vector3[2];
  26222. var currentScaling = BABYLON.Tmp.Vector3[3];
  26223. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26224. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26225. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26226. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26227. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26228. }
  26229. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26230. return originalAnimation._workValue;
  26231. };
  26232. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26233. var originalAnimation = holder.animations[0];
  26234. var originalValue = holder.originalValue;
  26235. if (holder.animations.length === 1) {
  26236. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26237. return refQuaternion;
  26238. }
  26239. var normalizer = 1.0;
  26240. var quaternions;
  26241. var weights;
  26242. if (holder.totalWeight < 1.0) {
  26243. var scale = 1.0 - holder.totalWeight;
  26244. quaternions = [];
  26245. weights = [];
  26246. quaternions.push(originalValue);
  26247. weights.push(scale);
  26248. }
  26249. else {
  26250. if (holder.animations.length === 2) { // Slerp as soon as we can
  26251. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26252. return refQuaternion;
  26253. }
  26254. quaternions = [];
  26255. weights = [];
  26256. normalizer = holder.totalWeight;
  26257. }
  26258. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26259. var runtimeAnimation = holder.animations[animIndex];
  26260. quaternions.push(runtimeAnimation.currentValue);
  26261. weights.push(runtimeAnimation.weight / normalizer);
  26262. }
  26263. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26264. var cumulativeAmount = 0;
  26265. var cumulativeQuaternion = null;
  26266. for (var index = 0; index < quaternions.length;) {
  26267. if (!cumulativeQuaternion) {
  26268. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26269. cumulativeQuaternion = refQuaternion;
  26270. cumulativeAmount = weights[index] + weights[index + 1];
  26271. index += 2;
  26272. continue;
  26273. }
  26274. cumulativeAmount += weights[index];
  26275. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26276. index++;
  26277. }
  26278. return cumulativeQuaternion;
  26279. };
  26280. Scene.prototype._processLateAnimationBindings = function () {
  26281. if (!this._registeredForLateAnimationBindings.length) {
  26282. return;
  26283. }
  26284. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26285. var target = this._registeredForLateAnimationBindings.data[index];
  26286. for (var path in target._lateAnimationHolders) {
  26287. var holder = target._lateAnimationHolders[path];
  26288. var originalAnimation = holder.animations[0];
  26289. var originalValue = holder.originalValue;
  26290. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26291. var finalValue = target[path];
  26292. if (matrixDecomposeMode) {
  26293. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26294. }
  26295. else {
  26296. var quaternionMode = originalValue.w !== undefined;
  26297. if (quaternionMode) {
  26298. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26299. }
  26300. else {
  26301. var startIndex = 0;
  26302. var normalizer = 1.0;
  26303. if (holder.totalWeight < 1.0) {
  26304. // We need to mix the original value in
  26305. if (originalValue.scale) {
  26306. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26307. }
  26308. else {
  26309. finalValue = originalValue * (1.0 - holder.totalWeight);
  26310. }
  26311. }
  26312. else {
  26313. // We need to normalize the weights
  26314. normalizer = holder.totalWeight;
  26315. var scale_1 = originalAnimation.weight / normalizer;
  26316. if (scale_1 !== 1) {
  26317. if (originalAnimation.currentValue.scale) {
  26318. finalValue = originalAnimation.currentValue.scale(scale_1);
  26319. }
  26320. else {
  26321. finalValue = originalAnimation.currentValue * scale_1;
  26322. }
  26323. }
  26324. else {
  26325. finalValue = originalAnimation.currentValue;
  26326. }
  26327. startIndex = 1;
  26328. }
  26329. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26330. var runtimeAnimation = holder.animations[animIndex];
  26331. var scale = runtimeAnimation.weight / normalizer;
  26332. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26333. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26334. }
  26335. else {
  26336. finalValue += runtimeAnimation.currentValue * scale;
  26337. }
  26338. }
  26339. }
  26340. }
  26341. target[path] = finalValue;
  26342. }
  26343. target._lateAnimationHolders = {};
  26344. }
  26345. this._registeredForLateAnimationBindings.reset();
  26346. };
  26347. // Matrix
  26348. /** @hidden */
  26349. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26350. this._useAlternateCameraConfiguration = active;
  26351. };
  26352. /**
  26353. * Gets the current view matrix
  26354. * @returns a Matrix
  26355. */
  26356. Scene.prototype.getViewMatrix = function () {
  26357. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26358. };
  26359. /**
  26360. * Gets the current projection matrix
  26361. * @returns a Matrix
  26362. */
  26363. Scene.prototype.getProjectionMatrix = function () {
  26364. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26365. };
  26366. /**
  26367. * Gets the current transform matrix
  26368. * @returns a Matrix made of View * Projection
  26369. */
  26370. Scene.prototype.getTransformMatrix = function () {
  26371. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26372. };
  26373. /**
  26374. * Sets the current transform matrix
  26375. * @param view defines the View matrix to use
  26376. * @param projection defines the Projection matrix to use
  26377. */
  26378. Scene.prototype.setTransformMatrix = function (view, projection) {
  26379. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26380. return;
  26381. }
  26382. this._viewUpdateFlag = view.updateFlag;
  26383. this._projectionUpdateFlag = projection.updateFlag;
  26384. this._viewMatrix = view;
  26385. this._projectionMatrix = projection;
  26386. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26387. // Update frustum
  26388. if (!this._frustumPlanes) {
  26389. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26390. }
  26391. else {
  26392. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26393. }
  26394. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26395. var otherCamera = this.activeCamera._alternateCamera;
  26396. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26397. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26398. }
  26399. if (this._sceneUbo.useUbo) {
  26400. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26401. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26402. this._sceneUbo.update();
  26403. }
  26404. };
  26405. /** @hidden */
  26406. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26407. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26408. return;
  26409. }
  26410. this._alternateViewUpdateFlag = view.updateFlag;
  26411. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26412. this._alternateViewMatrix = view;
  26413. this._alternateProjectionMatrix = projection;
  26414. if (!this._alternateTransformMatrix) {
  26415. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26416. }
  26417. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26418. if (!this._alternateSceneUbo) {
  26419. this._createAlternateUbo();
  26420. }
  26421. if (this._alternateSceneUbo.useUbo) {
  26422. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26423. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26424. this._alternateSceneUbo.update();
  26425. }
  26426. };
  26427. /**
  26428. * Gets the uniform buffer used to store scene data
  26429. * @returns a UniformBuffer
  26430. */
  26431. Scene.prototype.getSceneUniformBuffer = function () {
  26432. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26433. };
  26434. /**
  26435. * Gets an unique (relatively to the current scene) Id
  26436. * @returns an unique number for the scene
  26437. */
  26438. Scene.prototype.getUniqueId = function () {
  26439. var result = Scene._uniqueIdCounter;
  26440. Scene._uniqueIdCounter++;
  26441. return result;
  26442. };
  26443. /**
  26444. * Add a mesh to the list of scene's meshes
  26445. * @param newMesh defines the mesh to add
  26446. * @param recursive if all child meshes should also be added to the scene
  26447. */
  26448. Scene.prototype.addMesh = function (newMesh, recursive) {
  26449. var _this = this;
  26450. if (recursive === void 0) { recursive = false; }
  26451. this.meshes.push(newMesh);
  26452. //notify the collision coordinator
  26453. if (this.collisionCoordinator) {
  26454. this.collisionCoordinator.onMeshAdded(newMesh);
  26455. }
  26456. newMesh._resyncLightSources();
  26457. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26458. if (recursive) {
  26459. newMesh.getChildMeshes().forEach(function (m) {
  26460. _this.addMesh(m);
  26461. });
  26462. }
  26463. };
  26464. /**
  26465. * Remove a mesh for the list of scene's meshes
  26466. * @param toRemove defines the mesh to remove
  26467. * @param recursive if all child meshes should also be removed from the scene
  26468. * @returns the index where the mesh was in the mesh list
  26469. */
  26470. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26471. var _this = this;
  26472. if (recursive === void 0) { recursive = false; }
  26473. var index = this.meshes.indexOf(toRemove);
  26474. if (index !== -1) {
  26475. // Remove from the scene if mesh found
  26476. this.meshes.splice(index, 1);
  26477. }
  26478. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26479. if (recursive) {
  26480. toRemove.getChildMeshes().forEach(function (m) {
  26481. _this.removeMesh(m);
  26482. });
  26483. }
  26484. return index;
  26485. };
  26486. /**
  26487. * Add a transform node to the list of scene's transform nodes
  26488. * @param newTransformNode defines the transform node to add
  26489. */
  26490. Scene.prototype.addTransformNode = function (newTransformNode) {
  26491. this.transformNodes.push(newTransformNode);
  26492. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26493. };
  26494. /**
  26495. * Remove a transform node for the list of scene's transform nodes
  26496. * @param toRemove defines the transform node to remove
  26497. * @returns the index where the transform node was in the transform node list
  26498. */
  26499. Scene.prototype.removeTransformNode = function (toRemove) {
  26500. var index = this.transformNodes.indexOf(toRemove);
  26501. if (index !== -1) {
  26502. // Remove from the scene if found
  26503. this.transformNodes.splice(index, 1);
  26504. }
  26505. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26506. return index;
  26507. };
  26508. /**
  26509. * Remove a skeleton for the list of scene's skeletons
  26510. * @param toRemove defines the skeleton to remove
  26511. * @returns the index where the skeleton was in the skeleton list
  26512. */
  26513. Scene.prototype.removeSkeleton = function (toRemove) {
  26514. var index = this.skeletons.indexOf(toRemove);
  26515. if (index !== -1) {
  26516. // Remove from the scene if found
  26517. this.skeletons.splice(index, 1);
  26518. }
  26519. return index;
  26520. };
  26521. /**
  26522. * Remove a morph target for the list of scene's morph targets
  26523. * @param toRemove defines the morph target to remove
  26524. * @returns the index where the morph target was in the morph target list
  26525. */
  26526. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26527. var index = this.morphTargetManagers.indexOf(toRemove);
  26528. if (index !== -1) {
  26529. // Remove from the scene if found
  26530. this.morphTargetManagers.splice(index, 1);
  26531. }
  26532. return index;
  26533. };
  26534. /**
  26535. * Remove a light for the list of scene's lights
  26536. * @param toRemove defines the light to remove
  26537. * @returns the index where the light was in the light list
  26538. */
  26539. Scene.prototype.removeLight = function (toRemove) {
  26540. var index = this.lights.indexOf(toRemove);
  26541. if (index !== -1) {
  26542. // Remove from meshes
  26543. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26544. var mesh = _a[_i];
  26545. mesh._removeLightSource(toRemove);
  26546. }
  26547. // Remove from the scene if mesh found
  26548. this.lights.splice(index, 1);
  26549. this.sortLightsByPriority();
  26550. }
  26551. this.onLightRemovedObservable.notifyObservers(toRemove);
  26552. return index;
  26553. };
  26554. /**
  26555. * Remove a camera for the list of scene's cameras
  26556. * @param toRemove defines the camera to remove
  26557. * @returns the index where the camera was in the camera list
  26558. */
  26559. Scene.prototype.removeCamera = function (toRemove) {
  26560. var index = this.cameras.indexOf(toRemove);
  26561. if (index !== -1) {
  26562. // Remove from the scene if mesh found
  26563. this.cameras.splice(index, 1);
  26564. }
  26565. // Remove from activeCameras
  26566. var index2 = this.activeCameras.indexOf(toRemove);
  26567. if (index2 !== -1) {
  26568. // Remove from the scene if mesh found
  26569. this.activeCameras.splice(index2, 1);
  26570. }
  26571. // Reset the activeCamera
  26572. if (this.activeCamera === toRemove) {
  26573. if (this.cameras.length > 0) {
  26574. this.activeCamera = this.cameras[0];
  26575. }
  26576. else {
  26577. this.activeCamera = null;
  26578. }
  26579. }
  26580. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26581. return index;
  26582. };
  26583. /**
  26584. * Remove a particle system for the list of scene's particle systems
  26585. * @param toRemove defines the particle system to remove
  26586. * @returns the index where the particle system was in the particle system list
  26587. */
  26588. Scene.prototype.removeParticleSystem = function (toRemove) {
  26589. var index = this.particleSystems.indexOf(toRemove);
  26590. if (index !== -1) {
  26591. this.particleSystems.splice(index, 1);
  26592. }
  26593. return index;
  26594. };
  26595. /**
  26596. * Remove a animation for the list of scene's animations
  26597. * @param toRemove defines the animation to remove
  26598. * @returns the index where the animation was in the animation list
  26599. */
  26600. Scene.prototype.removeAnimation = function (toRemove) {
  26601. var index = this.animations.indexOf(toRemove);
  26602. if (index !== -1) {
  26603. this.animations.splice(index, 1);
  26604. }
  26605. return index;
  26606. };
  26607. /**
  26608. * Removes the given animation group from this scene.
  26609. * @param toRemove The animation group to remove
  26610. * @returns The index of the removed animation group
  26611. */
  26612. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26613. var index = this.animationGroups.indexOf(toRemove);
  26614. if (index !== -1) {
  26615. this.animationGroups.splice(index, 1);
  26616. }
  26617. return index;
  26618. };
  26619. /**
  26620. * Removes the given multi-material from this scene.
  26621. * @param toRemove The multi-material to remove
  26622. * @returns The index of the removed multi-material
  26623. */
  26624. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26625. var index = this.multiMaterials.indexOf(toRemove);
  26626. if (index !== -1) {
  26627. this.multiMaterials.splice(index, 1);
  26628. }
  26629. return index;
  26630. };
  26631. /**
  26632. * Removes the given material from this scene.
  26633. * @param toRemove The material to remove
  26634. * @returns The index of the removed material
  26635. */
  26636. Scene.prototype.removeMaterial = function (toRemove) {
  26637. var index = this.materials.indexOf(toRemove);
  26638. if (index !== -1) {
  26639. this.materials.splice(index, 1);
  26640. }
  26641. return index;
  26642. };
  26643. /**
  26644. * Removes the given action manager from this scene.
  26645. * @param toRemove The action manager to remove
  26646. * @returns The index of the removed action manager
  26647. */
  26648. Scene.prototype.removeActionManager = function (toRemove) {
  26649. var index = this.actionManagers.indexOf(toRemove);
  26650. if (index !== -1) {
  26651. this.actionManagers.splice(index, 1);
  26652. }
  26653. return index;
  26654. };
  26655. /**
  26656. * Removes the given texture from this scene.
  26657. * @param toRemove The texture to remove
  26658. * @returns The index of the removed texture
  26659. */
  26660. Scene.prototype.removeTexture = function (toRemove) {
  26661. var index = this.textures.indexOf(toRemove);
  26662. if (index !== -1) {
  26663. this.textures.splice(index, 1);
  26664. }
  26665. return index;
  26666. };
  26667. /**
  26668. * Adds the given light to this scene
  26669. * @param newLight The light to add
  26670. */
  26671. Scene.prototype.addLight = function (newLight) {
  26672. this.lights.push(newLight);
  26673. this.sortLightsByPriority();
  26674. // Add light to all meshes (To support if the light is removed and then readded)
  26675. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26676. var mesh = _a[_i];
  26677. if (mesh._lightSources.indexOf(newLight) === -1) {
  26678. mesh._lightSources.push(newLight);
  26679. mesh._resyncLightSources();
  26680. }
  26681. }
  26682. this.onNewLightAddedObservable.notifyObservers(newLight);
  26683. };
  26684. /**
  26685. * Sorts the list list based on light priorities
  26686. */
  26687. Scene.prototype.sortLightsByPriority = function () {
  26688. if (this.requireLightSorting) {
  26689. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26690. }
  26691. };
  26692. /**
  26693. * Adds the given camera to this scene
  26694. * @param newCamera The camera to add
  26695. */
  26696. Scene.prototype.addCamera = function (newCamera) {
  26697. this.cameras.push(newCamera);
  26698. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26699. };
  26700. /**
  26701. * Adds the given skeleton to this scene
  26702. * @param newSkeleton The skeleton to add
  26703. */
  26704. Scene.prototype.addSkeleton = function (newSkeleton) {
  26705. this.skeletons.push(newSkeleton);
  26706. };
  26707. /**
  26708. * Adds the given particle system to this scene
  26709. * @param newParticleSystem The particle system to add
  26710. */
  26711. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26712. this.particleSystems.push(newParticleSystem);
  26713. };
  26714. /**
  26715. * Adds the given animation to this scene
  26716. * @param newAnimation The animation to add
  26717. */
  26718. Scene.prototype.addAnimation = function (newAnimation) {
  26719. this.animations.push(newAnimation);
  26720. };
  26721. /**
  26722. * Adds the given animation group to this scene.
  26723. * @param newAnimationGroup The animation group to add
  26724. */
  26725. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26726. this.animationGroups.push(newAnimationGroup);
  26727. };
  26728. /**
  26729. * Adds the given multi-material to this scene
  26730. * @param newMultiMaterial The multi-material to add
  26731. */
  26732. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26733. this.multiMaterials.push(newMultiMaterial);
  26734. };
  26735. /**
  26736. * Adds the given material to this scene
  26737. * @param newMaterial The material to add
  26738. */
  26739. Scene.prototype.addMaterial = function (newMaterial) {
  26740. this.materials.push(newMaterial);
  26741. };
  26742. /**
  26743. * Adds the given morph target to this scene
  26744. * @param newMorphTargetManager The morph target to add
  26745. */
  26746. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26747. this.morphTargetManagers.push(newMorphTargetManager);
  26748. };
  26749. /**
  26750. * Adds the given geometry to this scene
  26751. * @param newGeometry The geometry to add
  26752. */
  26753. Scene.prototype.addGeometry = function (newGeometry) {
  26754. this.geometries.push(newGeometry);
  26755. };
  26756. /**
  26757. * Adds the given action manager to this scene
  26758. * @param newActionManager The action manager to add
  26759. */
  26760. Scene.prototype.addActionManager = function (newActionManager) {
  26761. this.actionManagers.push(newActionManager);
  26762. };
  26763. /**
  26764. * Adds the given texture to this scene.
  26765. * @param newTexture The texture to add
  26766. */
  26767. Scene.prototype.addTexture = function (newTexture) {
  26768. this.textures.push(newTexture);
  26769. };
  26770. /**
  26771. * Switch active camera
  26772. * @param newCamera defines the new active camera
  26773. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26774. */
  26775. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26776. if (attachControl === void 0) { attachControl = true; }
  26777. var canvas = this._engine.getRenderingCanvas();
  26778. if (!canvas) {
  26779. return;
  26780. }
  26781. if (this.activeCamera) {
  26782. this.activeCamera.detachControl(canvas);
  26783. }
  26784. this.activeCamera = newCamera;
  26785. if (attachControl) {
  26786. newCamera.attachControl(canvas);
  26787. }
  26788. };
  26789. /**
  26790. * sets the active camera of the scene using its ID
  26791. * @param id defines the camera's ID
  26792. * @return the new active camera or null if none found.
  26793. */
  26794. Scene.prototype.setActiveCameraByID = function (id) {
  26795. var camera = this.getCameraByID(id);
  26796. if (camera) {
  26797. this.activeCamera = camera;
  26798. return camera;
  26799. }
  26800. return null;
  26801. };
  26802. /**
  26803. * sets the active camera of the scene using its name
  26804. * @param name defines the camera's name
  26805. * @returns the new active camera or null if none found.
  26806. */
  26807. Scene.prototype.setActiveCameraByName = function (name) {
  26808. var camera = this.getCameraByName(name);
  26809. if (camera) {
  26810. this.activeCamera = camera;
  26811. return camera;
  26812. }
  26813. return null;
  26814. };
  26815. /**
  26816. * get an animation group using its name
  26817. * @param name defines the material's name
  26818. * @return the animation group or null if none found.
  26819. */
  26820. Scene.prototype.getAnimationGroupByName = function (name) {
  26821. for (var index = 0; index < this.animationGroups.length; index++) {
  26822. if (this.animationGroups[index].name === name) {
  26823. return this.animationGroups[index];
  26824. }
  26825. }
  26826. return null;
  26827. };
  26828. /**
  26829. * get a material using its id
  26830. * @param id defines the material's ID
  26831. * @return the material or null if none found.
  26832. */
  26833. Scene.prototype.getMaterialByID = function (id) {
  26834. for (var index = 0; index < this.materials.length; index++) {
  26835. if (this.materials[index].id === id) {
  26836. return this.materials[index];
  26837. }
  26838. }
  26839. return null;
  26840. };
  26841. /**
  26842. * Gets a material using its name
  26843. * @param name defines the material's name
  26844. * @return the material or null if none found.
  26845. */
  26846. Scene.prototype.getMaterialByName = function (name) {
  26847. for (var index = 0; index < this.materials.length; index++) {
  26848. if (this.materials[index].name === name) {
  26849. return this.materials[index];
  26850. }
  26851. }
  26852. return null;
  26853. };
  26854. /**
  26855. * Gets a camera using its id
  26856. * @param id defines the id to look for
  26857. * @returns the camera or null if not found
  26858. */
  26859. Scene.prototype.getCameraByID = function (id) {
  26860. for (var index = 0; index < this.cameras.length; index++) {
  26861. if (this.cameras[index].id === id) {
  26862. return this.cameras[index];
  26863. }
  26864. }
  26865. return null;
  26866. };
  26867. /**
  26868. * Gets a camera using its unique id
  26869. * @param uniqueId defines the unique id to look for
  26870. * @returns the camera or null if not found
  26871. */
  26872. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26873. for (var index = 0; index < this.cameras.length; index++) {
  26874. if (this.cameras[index].uniqueId === uniqueId) {
  26875. return this.cameras[index];
  26876. }
  26877. }
  26878. return null;
  26879. };
  26880. /**
  26881. * Gets a camera using its name
  26882. * @param name defines the camera's name
  26883. * @return the camera or null if none found.
  26884. */
  26885. Scene.prototype.getCameraByName = function (name) {
  26886. for (var index = 0; index < this.cameras.length; index++) {
  26887. if (this.cameras[index].name === name) {
  26888. return this.cameras[index];
  26889. }
  26890. }
  26891. return null;
  26892. };
  26893. /**
  26894. * Gets a bone using its id
  26895. * @param id defines the bone's id
  26896. * @return the bone or null if not found
  26897. */
  26898. Scene.prototype.getBoneByID = function (id) {
  26899. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26900. var skeleton = this.skeletons[skeletonIndex];
  26901. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26902. if (skeleton.bones[boneIndex].id === id) {
  26903. return skeleton.bones[boneIndex];
  26904. }
  26905. }
  26906. }
  26907. return null;
  26908. };
  26909. /**
  26910. * Gets a bone using its id
  26911. * @param name defines the bone's name
  26912. * @return the bone or null if not found
  26913. */
  26914. Scene.prototype.getBoneByName = function (name) {
  26915. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26916. var skeleton = this.skeletons[skeletonIndex];
  26917. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26918. if (skeleton.bones[boneIndex].name === name) {
  26919. return skeleton.bones[boneIndex];
  26920. }
  26921. }
  26922. }
  26923. return null;
  26924. };
  26925. /**
  26926. * Gets a light node using its name
  26927. * @param name defines the the light's name
  26928. * @return the light or null if none found.
  26929. */
  26930. Scene.prototype.getLightByName = function (name) {
  26931. for (var index = 0; index < this.lights.length; index++) {
  26932. if (this.lights[index].name === name) {
  26933. return this.lights[index];
  26934. }
  26935. }
  26936. return null;
  26937. };
  26938. /**
  26939. * Gets a light node using its id
  26940. * @param id defines the light's id
  26941. * @return the light or null if none found.
  26942. */
  26943. Scene.prototype.getLightByID = function (id) {
  26944. for (var index = 0; index < this.lights.length; index++) {
  26945. if (this.lights[index].id === id) {
  26946. return this.lights[index];
  26947. }
  26948. }
  26949. return null;
  26950. };
  26951. /**
  26952. * Gets a light node using its scene-generated unique ID
  26953. * @param uniqueId defines the light's unique id
  26954. * @return the light or null if none found.
  26955. */
  26956. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26957. for (var index = 0; index < this.lights.length; index++) {
  26958. if (this.lights[index].uniqueId === uniqueId) {
  26959. return this.lights[index];
  26960. }
  26961. }
  26962. return null;
  26963. };
  26964. /**
  26965. * Gets a particle system by id
  26966. * @param id defines the particle system id
  26967. * @return the corresponding system or null if none found
  26968. */
  26969. Scene.prototype.getParticleSystemByID = function (id) {
  26970. for (var index = 0; index < this.particleSystems.length; index++) {
  26971. if (this.particleSystems[index].id === id) {
  26972. return this.particleSystems[index];
  26973. }
  26974. }
  26975. return null;
  26976. };
  26977. /**
  26978. * Gets a geometry using its ID
  26979. * @param id defines the geometry's id
  26980. * @return the geometry or null if none found.
  26981. */
  26982. Scene.prototype.getGeometryByID = function (id) {
  26983. for (var index = 0; index < this.geometries.length; index++) {
  26984. if (this.geometries[index].id === id) {
  26985. return this.geometries[index];
  26986. }
  26987. }
  26988. return null;
  26989. };
  26990. /**
  26991. * Add a new geometry to this scene
  26992. * @param geometry defines the geometry to be added to the scene.
  26993. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26994. * @return a boolean defining if the geometry was added or not
  26995. */
  26996. Scene.prototype.pushGeometry = function (geometry, force) {
  26997. if (!force && this.getGeometryByID(geometry.id)) {
  26998. return false;
  26999. }
  27000. this.geometries.push(geometry);
  27001. //notify the collision coordinator
  27002. if (this.collisionCoordinator) {
  27003. this.collisionCoordinator.onGeometryAdded(geometry);
  27004. }
  27005. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27006. return true;
  27007. };
  27008. /**
  27009. * Removes an existing geometry
  27010. * @param geometry defines the geometry to be removed from the scene
  27011. * @return a boolean defining if the geometry was removed or not
  27012. */
  27013. Scene.prototype.removeGeometry = function (geometry) {
  27014. var index = this.geometries.indexOf(geometry);
  27015. if (index > -1) {
  27016. this.geometries.splice(index, 1);
  27017. //notify the collision coordinator
  27018. if (this.collisionCoordinator) {
  27019. this.collisionCoordinator.onGeometryDeleted(geometry);
  27020. }
  27021. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27022. return true;
  27023. }
  27024. return false;
  27025. };
  27026. /**
  27027. * Gets the list of geometries attached to the scene
  27028. * @returns an array of Geometry
  27029. */
  27030. Scene.prototype.getGeometries = function () {
  27031. return this.geometries;
  27032. };
  27033. /**
  27034. * Gets the first added mesh found of a given ID
  27035. * @param id defines the id to search for
  27036. * @return the mesh found or null if not found at all
  27037. */
  27038. Scene.prototype.getMeshByID = function (id) {
  27039. for (var index = 0; index < this.meshes.length; index++) {
  27040. if (this.meshes[index].id === id) {
  27041. return this.meshes[index];
  27042. }
  27043. }
  27044. return null;
  27045. };
  27046. /**
  27047. * Gets a list of meshes using their id
  27048. * @param id defines the id to search for
  27049. * @returns a list of meshes
  27050. */
  27051. Scene.prototype.getMeshesByID = function (id) {
  27052. return this.meshes.filter(function (m) {
  27053. return m.id === id;
  27054. });
  27055. };
  27056. /**
  27057. * Gets the first added transform node found of a given ID
  27058. * @param id defines the id to search for
  27059. * @return the found transform node or null if not found at all.
  27060. */
  27061. Scene.prototype.getTransformNodeByID = function (id) {
  27062. for (var index = 0; index < this.transformNodes.length; index++) {
  27063. if (this.transformNodes[index].id === id) {
  27064. return this.transformNodes[index];
  27065. }
  27066. }
  27067. return null;
  27068. };
  27069. /**
  27070. * Gets a list of transform nodes using their id
  27071. * @param id defines the id to search for
  27072. * @returns a list of transform nodes
  27073. */
  27074. Scene.prototype.getTransformNodesByID = function (id) {
  27075. return this.transformNodes.filter(function (m) {
  27076. return m.id === id;
  27077. });
  27078. };
  27079. /**
  27080. * Gets a mesh with its auto-generated unique id
  27081. * @param uniqueId defines the unique id to search for
  27082. * @return the found mesh or null if not found at all.
  27083. */
  27084. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27085. for (var index = 0; index < this.meshes.length; index++) {
  27086. if (this.meshes[index].uniqueId === uniqueId) {
  27087. return this.meshes[index];
  27088. }
  27089. }
  27090. return null;
  27091. };
  27092. /**
  27093. * Gets a the last added mesh using a given id
  27094. * @param id defines the id to search for
  27095. * @return the found mesh or null if not found at all.
  27096. */
  27097. Scene.prototype.getLastMeshByID = function (id) {
  27098. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27099. if (this.meshes[index].id === id) {
  27100. return this.meshes[index];
  27101. }
  27102. }
  27103. return null;
  27104. };
  27105. /**
  27106. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27107. * @param id defines the id to search for
  27108. * @return the found node or null if not found at all
  27109. */
  27110. Scene.prototype.getLastEntryByID = function (id) {
  27111. var index;
  27112. for (index = this.meshes.length - 1; index >= 0; index--) {
  27113. if (this.meshes[index].id === id) {
  27114. return this.meshes[index];
  27115. }
  27116. }
  27117. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27118. if (this.transformNodes[index].id === id) {
  27119. return this.transformNodes[index];
  27120. }
  27121. }
  27122. for (index = this.cameras.length - 1; index >= 0; index--) {
  27123. if (this.cameras[index].id === id) {
  27124. return this.cameras[index];
  27125. }
  27126. }
  27127. for (index = this.lights.length - 1; index >= 0; index--) {
  27128. if (this.lights[index].id === id) {
  27129. return this.lights[index];
  27130. }
  27131. }
  27132. return null;
  27133. };
  27134. /**
  27135. * Gets a node (Mesh, Camera, Light) using a given id
  27136. * @param id defines the id to search for
  27137. * @return the found node or null if not found at all
  27138. */
  27139. Scene.prototype.getNodeByID = function (id) {
  27140. var mesh = this.getMeshByID(id);
  27141. if (mesh) {
  27142. return mesh;
  27143. }
  27144. var light = this.getLightByID(id);
  27145. if (light) {
  27146. return light;
  27147. }
  27148. var camera = this.getCameraByID(id);
  27149. if (camera) {
  27150. return camera;
  27151. }
  27152. var bone = this.getBoneByID(id);
  27153. return bone;
  27154. };
  27155. /**
  27156. * Gets a node (Mesh, Camera, Light) using a given name
  27157. * @param name defines the name to search for
  27158. * @return the found node or null if not found at all.
  27159. */
  27160. Scene.prototype.getNodeByName = function (name) {
  27161. var mesh = this.getMeshByName(name);
  27162. if (mesh) {
  27163. return mesh;
  27164. }
  27165. var light = this.getLightByName(name);
  27166. if (light) {
  27167. return light;
  27168. }
  27169. var camera = this.getCameraByName(name);
  27170. if (camera) {
  27171. return camera;
  27172. }
  27173. var bone = this.getBoneByName(name);
  27174. return bone;
  27175. };
  27176. /**
  27177. * Gets a mesh using a given name
  27178. * @param name defines the name to search for
  27179. * @return the found mesh or null if not found at all.
  27180. */
  27181. Scene.prototype.getMeshByName = function (name) {
  27182. for (var index = 0; index < this.meshes.length; index++) {
  27183. if (this.meshes[index].name === name) {
  27184. return this.meshes[index];
  27185. }
  27186. }
  27187. return null;
  27188. };
  27189. /**
  27190. * Gets a transform node using a given name
  27191. * @param name defines the name to search for
  27192. * @return the found transform node or null if not found at all.
  27193. */
  27194. Scene.prototype.getTransformNodeByName = function (name) {
  27195. for (var index = 0; index < this.transformNodes.length; index++) {
  27196. if (this.transformNodes[index].name === name) {
  27197. return this.transformNodes[index];
  27198. }
  27199. }
  27200. return null;
  27201. };
  27202. /**
  27203. * Gets a sound using a given name
  27204. * @param name defines the name to search for
  27205. * @return the found sound or null if not found at all.
  27206. */
  27207. Scene.prototype.getSoundByName = function (name) {
  27208. var index;
  27209. if (BABYLON.AudioEngine) {
  27210. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27211. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27212. return this.mainSoundTrack.soundCollection[index];
  27213. }
  27214. }
  27215. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27216. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27217. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27218. return this.soundTracks[sdIndex].soundCollection[index];
  27219. }
  27220. }
  27221. }
  27222. }
  27223. return null;
  27224. };
  27225. /**
  27226. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27227. * @param id defines the id to search for
  27228. * @return the found skeleton or null if not found at all.
  27229. */
  27230. Scene.prototype.getLastSkeletonByID = function (id) {
  27231. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27232. if (this.skeletons[index].id === id) {
  27233. return this.skeletons[index];
  27234. }
  27235. }
  27236. return null;
  27237. };
  27238. /**
  27239. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27240. * @param id defines the id to search for
  27241. * @return the found skeleton or null if not found at all.
  27242. */
  27243. Scene.prototype.getSkeletonById = function (id) {
  27244. for (var index = 0; index < this.skeletons.length; index++) {
  27245. if (this.skeletons[index].id === id) {
  27246. return this.skeletons[index];
  27247. }
  27248. }
  27249. return null;
  27250. };
  27251. /**
  27252. * Gets a skeleton using a given name
  27253. * @param name defines the name to search for
  27254. * @return the found skeleton or null if not found at all.
  27255. */
  27256. Scene.prototype.getSkeletonByName = function (name) {
  27257. for (var index = 0; index < this.skeletons.length; index++) {
  27258. if (this.skeletons[index].name === name) {
  27259. return this.skeletons[index];
  27260. }
  27261. }
  27262. return null;
  27263. };
  27264. /**
  27265. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27266. * @param id defines the id to search for
  27267. * @return the found morph target manager or null if not found at all.
  27268. */
  27269. Scene.prototype.getMorphTargetManagerById = function (id) {
  27270. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27271. if (this.morphTargetManagers[index].uniqueId === id) {
  27272. return this.morphTargetManagers[index];
  27273. }
  27274. }
  27275. return null;
  27276. };
  27277. /**
  27278. * Gets a boolean indicating if the given mesh is active
  27279. * @param mesh defines the mesh to look for
  27280. * @returns true if the mesh is in the active list
  27281. */
  27282. Scene.prototype.isActiveMesh = function (mesh) {
  27283. return (this._activeMeshes.indexOf(mesh) !== -1);
  27284. };
  27285. Object.defineProperty(Scene.prototype, "uid", {
  27286. /**
  27287. * Return a unique id as a string which can serve as an identifier for the scene
  27288. */
  27289. get: function () {
  27290. if (!this._uid) {
  27291. this._uid = BABYLON.Tools.RandomId();
  27292. }
  27293. return this._uid;
  27294. },
  27295. enumerable: true,
  27296. configurable: true
  27297. });
  27298. /**
  27299. * Add an externaly attached data from its key.
  27300. * This method call will fail and return false, if such key already exists.
  27301. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27302. * @param key the unique key that identifies the data
  27303. * @param data the data object to associate to the key for this Engine instance
  27304. * @return true if no such key were already present and the data was added successfully, false otherwise
  27305. */
  27306. Scene.prototype.addExternalData = function (key, data) {
  27307. if (!this._externalData) {
  27308. this._externalData = new BABYLON.StringDictionary();
  27309. }
  27310. return this._externalData.add(key, data);
  27311. };
  27312. /**
  27313. * Get an externaly attached data from its key
  27314. * @param key the unique key that identifies the data
  27315. * @return the associated data, if present (can be null), or undefined if not present
  27316. */
  27317. Scene.prototype.getExternalData = function (key) {
  27318. if (!this._externalData) {
  27319. return null;
  27320. }
  27321. return this._externalData.get(key);
  27322. };
  27323. /**
  27324. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27325. * @param key the unique key that identifies the data
  27326. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27327. * @return the associated data, can be null if the factory returned null.
  27328. */
  27329. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27330. if (!this._externalData) {
  27331. this._externalData = new BABYLON.StringDictionary();
  27332. }
  27333. return this._externalData.getOrAddWithFactory(key, factory);
  27334. };
  27335. /**
  27336. * Remove an externaly attached data from the Engine instance
  27337. * @param key the unique key that identifies the data
  27338. * @return true if the data was successfully removed, false if it doesn't exist
  27339. */
  27340. Scene.prototype.removeExternalData = function (key) {
  27341. return this._externalData.remove(key);
  27342. };
  27343. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27344. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27345. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27346. var step = _a[_i];
  27347. step.action(mesh, subMesh);
  27348. }
  27349. var material = subMesh.getMaterial();
  27350. if (material !== null && material !== undefined) {
  27351. // Render targets
  27352. if (material.getRenderTargetTextures !== undefined) {
  27353. if (this._processedMaterials.indexOf(material) === -1) {
  27354. this._processedMaterials.push(material);
  27355. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27356. }
  27357. }
  27358. // Dispatch
  27359. this._activeIndices.addCount(subMesh.indexCount, false);
  27360. this._renderingManager.dispatch(subMesh, mesh, material);
  27361. }
  27362. }
  27363. };
  27364. /**
  27365. * Clear the processed materials smart array preventing retention point in material dispose.
  27366. */
  27367. Scene.prototype.freeProcessedMaterials = function () {
  27368. this._processedMaterials.dispose();
  27369. };
  27370. /**
  27371. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27372. */
  27373. Scene.prototype.freeActiveMeshes = function () {
  27374. this._activeMeshes.dispose();
  27375. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27376. this.activeCamera._activeMeshes.dispose();
  27377. }
  27378. if (this.activeCameras) {
  27379. for (var i = 0; i < this.activeCameras.length; i++) {
  27380. var activeCamera = this.activeCameras[i];
  27381. if (activeCamera && activeCamera._activeMeshes) {
  27382. activeCamera._activeMeshes.dispose();
  27383. }
  27384. }
  27385. }
  27386. };
  27387. /**
  27388. * Clear the info related to rendering groups preventing retention points during dispose.
  27389. */
  27390. Scene.prototype.freeRenderingGroups = function () {
  27391. if (this._renderingManager) {
  27392. this._renderingManager.freeRenderingGroups();
  27393. }
  27394. if (this.textures) {
  27395. for (var i = 0; i < this.textures.length; i++) {
  27396. var texture = this.textures[i];
  27397. if (texture && texture.renderList) {
  27398. texture.freeRenderingGroups();
  27399. }
  27400. }
  27401. }
  27402. };
  27403. /** @hidden */
  27404. Scene.prototype._isInIntermediateRendering = function () {
  27405. return this._intermediateRendering;
  27406. };
  27407. /**
  27408. * Defines the current active mesh candidate provider
  27409. * @param provider defines the provider to use
  27410. */
  27411. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27412. this._activeMeshCandidateProvider = provider;
  27413. };
  27414. /**
  27415. * Gets the current active mesh candidate provider
  27416. * @returns the current active mesh candidate provider
  27417. */
  27418. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27419. return this._activeMeshCandidateProvider;
  27420. };
  27421. /**
  27422. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27423. * @returns the current scene
  27424. */
  27425. Scene.prototype.freezeActiveMeshes = function () {
  27426. if (!this.activeCamera) {
  27427. return this;
  27428. }
  27429. if (!this._frustumPlanes) {
  27430. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27431. }
  27432. this._evaluateActiveMeshes();
  27433. this._activeMeshesFrozen = true;
  27434. return this;
  27435. };
  27436. /**
  27437. * Use this function to restart evaluating active meshes on every frame
  27438. * @returns the current scene
  27439. */
  27440. Scene.prototype.unfreezeActiveMeshes = function () {
  27441. this._activeMeshesFrozen = false;
  27442. return this;
  27443. };
  27444. Scene.prototype._evaluateActiveMeshes = function () {
  27445. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27446. return;
  27447. }
  27448. if (!this.activeCamera) {
  27449. return;
  27450. }
  27451. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27452. this.activeCamera._activeMeshes.reset();
  27453. this._activeMeshes.reset();
  27454. this._renderingManager.reset();
  27455. this._processedMaterials.reset();
  27456. this._activeParticleSystems.reset();
  27457. this._activeSkeletons.reset();
  27458. this._softwareSkinnedMeshes.reset();
  27459. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27460. var step = _a[_i];
  27461. step.action();
  27462. }
  27463. // Meshes
  27464. var meshes;
  27465. var len;
  27466. var checkIsEnabled = true;
  27467. // Determine mesh candidates
  27468. if (this._activeMeshCandidateProvider !== undefined) {
  27469. // Use _activeMeshCandidateProvider
  27470. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27471. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27472. if (meshes !== undefined) {
  27473. len = meshes.length;
  27474. }
  27475. else {
  27476. len = 0;
  27477. }
  27478. }
  27479. else if (this._selectionOctree !== undefined) {
  27480. // Octree
  27481. var selection = this._selectionOctree.select(this._frustumPlanes);
  27482. meshes = selection.data;
  27483. len = selection.length;
  27484. }
  27485. else {
  27486. // Full scene traversal
  27487. len = this.meshes.length;
  27488. meshes = this.meshes;
  27489. }
  27490. // Check each mesh
  27491. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27492. mesh = meshes[meshIndex];
  27493. if (mesh.isBlocked) {
  27494. continue;
  27495. }
  27496. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27497. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27498. continue;
  27499. }
  27500. mesh.computeWorldMatrix();
  27501. // Intersections
  27502. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27503. this._meshesForIntersections.pushNoDuplicate(mesh);
  27504. }
  27505. // Switch to current LOD
  27506. meshLOD = mesh.getLOD(this.activeCamera);
  27507. if (meshLOD === undefined || meshLOD === null) {
  27508. continue;
  27509. }
  27510. mesh._preActivate();
  27511. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27512. this._activeMeshes.push(mesh);
  27513. this.activeCamera._activeMeshes.push(mesh);
  27514. mesh._activate(this._renderId);
  27515. if (meshLOD !== mesh) {
  27516. meshLOD._activate(this._renderId);
  27517. }
  27518. this._activeMesh(mesh, meshLOD);
  27519. }
  27520. }
  27521. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27522. // Particle systems
  27523. if (this.particlesEnabled) {
  27524. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27525. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27526. var particleSystem = this.particleSystems[particleIndex];
  27527. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27528. continue;
  27529. }
  27530. var emitter = particleSystem.emitter;
  27531. if (!emitter.position || emitter.isEnabled()) {
  27532. this._activeParticleSystems.push(particleSystem);
  27533. particleSystem.animate();
  27534. this._renderingManager.dispatchParticles(particleSystem);
  27535. }
  27536. }
  27537. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27538. }
  27539. };
  27540. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27541. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27542. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27543. mesh.skeleton.prepare();
  27544. }
  27545. if (!mesh.computeBonesUsingShaders) {
  27546. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27547. }
  27548. }
  27549. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27550. var step = _a[_i];
  27551. step.action(sourceMesh, mesh);
  27552. }
  27553. if (mesh !== undefined && mesh !== null
  27554. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27555. // Submeshes Octrees
  27556. var len;
  27557. var subMeshes;
  27558. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27559. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27560. len = intersections.length;
  27561. subMeshes = intersections.data;
  27562. }
  27563. else {
  27564. subMeshes = mesh.subMeshes;
  27565. len = subMeshes.length;
  27566. }
  27567. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27568. subMesh = subMeshes[subIndex];
  27569. this._evaluateSubMesh(subMesh, mesh);
  27570. }
  27571. }
  27572. };
  27573. /**
  27574. * Update the transform matrix to update from the current active camera
  27575. * @param force defines a boolean used to force the update even if cache is up to date
  27576. */
  27577. Scene.prototype.updateTransformMatrix = function (force) {
  27578. if (!this.activeCamera) {
  27579. return;
  27580. }
  27581. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27582. };
  27583. /**
  27584. * 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)
  27585. * @param alternateCamera defines the camera to use
  27586. */
  27587. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27588. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27589. };
  27590. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27591. if (camera && camera._skipRendering) {
  27592. return;
  27593. }
  27594. var engine = this._engine;
  27595. this.activeCamera = camera;
  27596. if (!this.activeCamera)
  27597. throw new Error("Active camera not set");
  27598. // Viewport
  27599. engine.setViewport(this.activeCamera.viewport);
  27600. // Camera
  27601. this.resetCachedMaterial();
  27602. this._renderId++;
  27603. this.updateTransformMatrix();
  27604. if (camera._alternateCamera) {
  27605. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27606. this._alternateRendering = true;
  27607. }
  27608. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27609. // Meshes
  27610. this._evaluateActiveMeshes();
  27611. // Software skinning
  27612. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27613. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27614. mesh.applySkeleton(mesh.skeleton);
  27615. }
  27616. // Render targets
  27617. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27618. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27619. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27620. }
  27621. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27622. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27623. }
  27624. if (this.renderTargetsEnabled) {
  27625. this._intermediateRendering = true;
  27626. if (this._renderTargets.length > 0) {
  27627. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27628. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27629. var renderTarget = this._renderTargets.data[renderIndex];
  27630. if (renderTarget._shouldRender()) {
  27631. this._renderId++;
  27632. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27633. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27634. }
  27635. }
  27636. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27637. this._renderId++;
  27638. }
  27639. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27640. var step = _a[_i];
  27641. step.action(this.activeCamera);
  27642. }
  27643. this._intermediateRendering = false;
  27644. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27645. }
  27646. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27647. // Prepare Frame
  27648. if (this.postProcessManager) {
  27649. this.postProcessManager._prepareFrame();
  27650. }
  27651. // Before Camera Draw
  27652. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27653. var step = _c[_b];
  27654. step.action(this.activeCamera);
  27655. }
  27656. // Render
  27657. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27658. this._renderingManager.render(null, null, true, true);
  27659. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27660. // After Camera Draw
  27661. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27662. var step = _e[_d];
  27663. step.action(this.activeCamera);
  27664. }
  27665. // Finalize frame
  27666. if (this.postProcessManager) {
  27667. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27668. }
  27669. // Reset some special arrays
  27670. this._renderTargets.reset();
  27671. this._alternateRendering = false;
  27672. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27673. };
  27674. Scene.prototype._processSubCameras = function (camera) {
  27675. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27676. this._renderForCamera(camera);
  27677. return;
  27678. }
  27679. // rig cameras
  27680. for (var index = 0; index < camera._rigCameras.length; index++) {
  27681. this._renderForCamera(camera._rigCameras[index], camera);
  27682. }
  27683. this.activeCamera = camera;
  27684. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27685. };
  27686. Scene.prototype._checkIntersections = function () {
  27687. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27688. var sourceMesh = this._meshesForIntersections.data[index];
  27689. if (!sourceMesh.actionManager) {
  27690. continue;
  27691. }
  27692. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27693. var action = sourceMesh.actionManager.actions[actionIndex];
  27694. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27695. var parameters = action.getTriggerParameter();
  27696. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27697. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27698. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27699. if (areIntersecting && currentIntersectionInProgress === -1) {
  27700. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27701. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27702. sourceMesh._intersectionsInProgress.push(otherMesh);
  27703. }
  27704. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27705. sourceMesh._intersectionsInProgress.push(otherMesh);
  27706. }
  27707. }
  27708. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27709. //They intersected, and now they don't.
  27710. //is this trigger an exit trigger? execute an event.
  27711. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27712. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27713. }
  27714. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27715. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27716. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27717. return otherMesh === parameterMesh;
  27718. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27719. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27720. }
  27721. }
  27722. }
  27723. }
  27724. }
  27725. };
  27726. /**
  27727. * Render the scene
  27728. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27729. */
  27730. Scene.prototype.render = function (updateCameras) {
  27731. if (updateCameras === void 0) { updateCameras = true; }
  27732. if (this.isDisposed) {
  27733. return;
  27734. }
  27735. // Register components that have been associated lately to the scene.
  27736. this._registerTransientComponents();
  27737. this._activeParticles.fetchNewFrame();
  27738. this._totalVertices.fetchNewFrame();
  27739. this._activeIndices.fetchNewFrame();
  27740. this._activeBones.fetchNewFrame();
  27741. this._meshesForIntersections.reset();
  27742. this.resetCachedMaterial();
  27743. this.onBeforeAnimationsObservable.notifyObservers(this);
  27744. // Actions
  27745. if (this.actionManager) {
  27746. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27747. }
  27748. if (this._engine.isDeterministicLockStep()) {
  27749. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27750. var defaultFPS = (60.0 / 1000.0);
  27751. var defaultFrameTime = 1000 / 60; // frame time in MS
  27752. if (this._physicsEngine) {
  27753. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27754. }
  27755. var stepsTaken = 0;
  27756. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27757. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27758. internalSteps = Math.min(internalSteps, maxSubSteps);
  27759. do {
  27760. this.onBeforeStepObservable.notifyObservers(this);
  27761. // Animations
  27762. this._animationRatio = defaultFrameTime * defaultFPS;
  27763. this._animate();
  27764. this.onAfterAnimationsObservable.notifyObservers(this);
  27765. // Physics
  27766. if (this._physicsEngine) {
  27767. this.onBeforePhysicsObservable.notifyObservers(this);
  27768. this._physicsEngine._step(defaultFrameTime / 1000);
  27769. this.onAfterPhysicsObservable.notifyObservers(this);
  27770. }
  27771. this.onAfterStepObservable.notifyObservers(this);
  27772. this._currentStepId++;
  27773. stepsTaken++;
  27774. deltaTime -= defaultFrameTime;
  27775. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27776. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27777. }
  27778. else {
  27779. // Animations
  27780. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27781. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27782. this._animate();
  27783. this.onAfterAnimationsObservable.notifyObservers(this);
  27784. // Physics
  27785. if (this._physicsEngine) {
  27786. this.onBeforePhysicsObservable.notifyObservers(this);
  27787. this._physicsEngine._step(deltaTime / 1000.0);
  27788. this.onAfterPhysicsObservable.notifyObservers(this);
  27789. }
  27790. }
  27791. // Before camera update steps
  27792. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27793. var step = _a[_i];
  27794. step.action();
  27795. }
  27796. // Update Cameras
  27797. if (updateCameras) {
  27798. if (this.activeCameras.length > 0) {
  27799. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27800. var camera = this.activeCameras[cameraIndex];
  27801. camera.update();
  27802. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27803. // rig cameras
  27804. for (var index = 0; index < camera._rigCameras.length; index++) {
  27805. camera._rigCameras[index].update();
  27806. }
  27807. }
  27808. }
  27809. }
  27810. else if (this.activeCamera) {
  27811. this.activeCamera.update();
  27812. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27813. // rig cameras
  27814. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27815. this.activeCamera._rigCameras[index].update();
  27816. }
  27817. }
  27818. }
  27819. }
  27820. // Before render
  27821. this.onBeforeRenderObservable.notifyObservers(this);
  27822. // Customs render targets
  27823. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27824. var engine = this.getEngine();
  27825. var currentActiveCamera = this.activeCamera;
  27826. if (this.renderTargetsEnabled) {
  27827. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27828. this._intermediateRendering = true;
  27829. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27830. var renderTarget = this.customRenderTargets[customIndex];
  27831. if (renderTarget._shouldRender()) {
  27832. this._renderId++;
  27833. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27834. if (!this.activeCamera)
  27835. throw new Error("Active camera not set");
  27836. // Viewport
  27837. engine.setViewport(this.activeCamera.viewport);
  27838. // Camera
  27839. this.updateTransformMatrix();
  27840. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27841. }
  27842. }
  27843. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27844. this._intermediateRendering = false;
  27845. this._renderId++;
  27846. }
  27847. // Restore back buffer
  27848. if (this.customRenderTargets.length > 0) {
  27849. engine.restoreDefaultFramebuffer();
  27850. }
  27851. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27852. this.activeCamera = currentActiveCamera;
  27853. // Procedural textures
  27854. if (this.proceduralTexturesEnabled) {
  27855. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27856. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27857. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27858. if (proceduralTexture._shouldRender()) {
  27859. proceduralTexture.render();
  27860. }
  27861. }
  27862. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27863. }
  27864. // Clear
  27865. if (this.autoClearDepthAndStencil || this.autoClear) {
  27866. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27867. }
  27868. // Shadows
  27869. if (this.shadowsEnabled) {
  27870. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27871. var light = this.lights[lightIndex];
  27872. var shadowGenerator = light.getShadowGenerator();
  27873. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27874. var shadowMap = (shadowGenerator.getShadowMap());
  27875. if (this.textures.indexOf(shadowMap) !== -1) {
  27876. this._renderTargets.push(shadowMap);
  27877. }
  27878. }
  27879. }
  27880. }
  27881. // Collects render targets from external components.
  27882. for (var _b = 0, _c = this._gatherRenderTargetsStage; _b < _c.length; _b++) {
  27883. var step = _c[_b];
  27884. step.action(this._renderTargets);
  27885. }
  27886. // Multi-cameras?
  27887. if (this.activeCameras.length > 0) {
  27888. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27889. if (cameraIndex > 0) {
  27890. this._engine.clear(null, false, true, true);
  27891. }
  27892. this._processSubCameras(this.activeCameras[cameraIndex]);
  27893. }
  27894. }
  27895. else {
  27896. if (!this.activeCamera) {
  27897. throw new Error("No camera defined");
  27898. }
  27899. this._processSubCameras(this.activeCamera);
  27900. }
  27901. // Intersection checks
  27902. this._checkIntersections();
  27903. // Update the audio listener attached to the camera
  27904. if (BABYLON.AudioEngine) {
  27905. this._updateAudioParameters();
  27906. }
  27907. // After render
  27908. if (this.afterRender) {
  27909. this.afterRender();
  27910. }
  27911. this.onAfterRenderObservable.notifyObservers(this);
  27912. // Cleaning
  27913. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27914. var data = this._toBeDisposed.data[index];
  27915. if (data) {
  27916. data.dispose();
  27917. }
  27918. this._toBeDisposed[index] = null;
  27919. }
  27920. this._toBeDisposed.reset();
  27921. if (this.dumpNextRenderTargets) {
  27922. this.dumpNextRenderTargets = false;
  27923. }
  27924. this._activeBones.addCount(0, true);
  27925. this._activeIndices.addCount(0, true);
  27926. this._activeParticles.addCount(0, true);
  27927. };
  27928. Scene.prototype._updateAudioParameters = function () {
  27929. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27930. return;
  27931. }
  27932. var listeningCamera;
  27933. var audioEngine = BABYLON.Engine.audioEngine;
  27934. if (this.activeCameras.length > 0) {
  27935. listeningCamera = this.activeCameras[0];
  27936. }
  27937. else {
  27938. listeningCamera = this.activeCamera;
  27939. }
  27940. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27941. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27942. // for VR cameras
  27943. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27944. listeningCamera = listeningCamera.rigCameras[0];
  27945. }
  27946. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27947. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27948. cameraDirection.normalize();
  27949. // To avoid some errors on GearVR
  27950. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27951. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27952. }
  27953. var i;
  27954. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27955. var sound = this.mainSoundTrack.soundCollection[i];
  27956. if (sound.useCustomAttenuation) {
  27957. sound.updateDistanceFromListener();
  27958. }
  27959. }
  27960. for (i = 0; i < this.soundTracks.length; i++) {
  27961. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27962. sound = this.soundTracks[i].soundCollection[j];
  27963. if (sound.useCustomAttenuation) {
  27964. sound.updateDistanceFromListener();
  27965. }
  27966. }
  27967. }
  27968. }
  27969. };
  27970. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27971. // Audio
  27972. /**
  27973. * Gets or sets if audio support is enabled
  27974. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27975. */
  27976. get: function () {
  27977. return this._audioEnabled;
  27978. },
  27979. set: function (value) {
  27980. this._audioEnabled = value;
  27981. if (BABYLON.AudioEngine) {
  27982. if (this._audioEnabled) {
  27983. this._enableAudio();
  27984. }
  27985. else {
  27986. this._disableAudio();
  27987. }
  27988. }
  27989. },
  27990. enumerable: true,
  27991. configurable: true
  27992. });
  27993. Scene.prototype._disableAudio = function () {
  27994. var i;
  27995. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27996. this.mainSoundTrack.soundCollection[i].pause();
  27997. }
  27998. for (i = 0; i < this.soundTracks.length; i++) {
  27999. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28000. this.soundTracks[i].soundCollection[j].pause();
  28001. }
  28002. }
  28003. };
  28004. Scene.prototype._enableAudio = function () {
  28005. var i;
  28006. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28007. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28008. this.mainSoundTrack.soundCollection[i].play();
  28009. }
  28010. }
  28011. for (i = 0; i < this.soundTracks.length; i++) {
  28012. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28013. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28014. this.soundTracks[i].soundCollection[j].play();
  28015. }
  28016. }
  28017. }
  28018. };
  28019. Object.defineProperty(Scene.prototype, "headphone", {
  28020. /**
  28021. * Gets or sets if audio will be output to headphones
  28022. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28023. */
  28024. get: function () {
  28025. return this._headphone;
  28026. },
  28027. set: function (value) {
  28028. this._headphone = value;
  28029. if (BABYLON.AudioEngine) {
  28030. if (this._headphone) {
  28031. this._switchAudioModeForHeadphones();
  28032. }
  28033. else {
  28034. this._switchAudioModeForNormalSpeakers();
  28035. }
  28036. }
  28037. },
  28038. enumerable: true,
  28039. configurable: true
  28040. });
  28041. Scene.prototype._switchAudioModeForHeadphones = function () {
  28042. this.mainSoundTrack.switchPanningModelToHRTF();
  28043. for (var i = 0; i < this.soundTracks.length; i++) {
  28044. this.soundTracks[i].switchPanningModelToHRTF();
  28045. }
  28046. };
  28047. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28048. this.mainSoundTrack.switchPanningModelToEqualPower();
  28049. for (var i = 0; i < this.soundTracks.length; i++) {
  28050. this.soundTracks[i].switchPanningModelToEqualPower();
  28051. }
  28052. };
  28053. /**
  28054. * Freeze all materials
  28055. * A frozen material will not be updatable but should be faster to render
  28056. */
  28057. Scene.prototype.freezeMaterials = function () {
  28058. for (var i = 0; i < this.materials.length; i++) {
  28059. this.materials[i].freeze();
  28060. }
  28061. };
  28062. /**
  28063. * Unfreeze all materials
  28064. * A frozen material will not be updatable but should be faster to render
  28065. */
  28066. Scene.prototype.unfreezeMaterials = function () {
  28067. for (var i = 0; i < this.materials.length; i++) {
  28068. this.materials[i].unfreeze();
  28069. }
  28070. };
  28071. /**
  28072. * Releases all held ressources
  28073. */
  28074. Scene.prototype.dispose = function () {
  28075. this.beforeRender = null;
  28076. this.afterRender = null;
  28077. this.skeletons = [];
  28078. this.morphTargetManagers = [];
  28079. this._transientComponents = [];
  28080. this._isReadyForMeshStage.clear();
  28081. this._beforeEvaluateActiveMeshStage.clear();
  28082. this._evaluateSubMeshStage.clear();
  28083. this._activeMeshStage.clear();
  28084. this._cameraDrawRenderTargetStage.clear();
  28085. this._beforeCameraDrawStage.clear();
  28086. this._beforeRenderingGroupDrawStage.clear();
  28087. this._afterRenderingGroupDrawStage.clear();
  28088. this._afterCameraDrawStage.clear();
  28089. this._beforeCameraUpdateStage.clear();
  28090. this._gatherRenderTargetsStage.clear();
  28091. this._rebuildGeometryStage.clear();
  28092. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28093. var component = _a[_i];
  28094. component.dispose();
  28095. }
  28096. this.importedMeshesFiles = new Array();
  28097. this.stopAllAnimations();
  28098. this.resetCachedMaterial();
  28099. // Smart arrays
  28100. if (this.activeCamera) {
  28101. this.activeCamera._activeMeshes.dispose();
  28102. this.activeCamera = null;
  28103. }
  28104. this._activeMeshes.dispose();
  28105. this._renderingManager.dispose();
  28106. this._processedMaterials.dispose();
  28107. this._activeParticleSystems.dispose();
  28108. this._activeSkeletons.dispose();
  28109. this._softwareSkinnedMeshes.dispose();
  28110. this._renderTargets.dispose();
  28111. this._registeredForLateAnimationBindings.dispose();
  28112. this._meshesForIntersections.dispose();
  28113. this._toBeDisposed.dispose();
  28114. // Abort active requests
  28115. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28116. var request = _c[_b];
  28117. request.abort();
  28118. }
  28119. // Debug layer
  28120. if (this._debugLayer) {
  28121. this._debugLayer.hide();
  28122. }
  28123. // Events
  28124. this.onDisposeObservable.notifyObservers(this);
  28125. this.onDisposeObservable.clear();
  28126. this.onBeforeRenderObservable.clear();
  28127. this.onAfterRenderObservable.clear();
  28128. this.onBeforeRenderTargetsRenderObservable.clear();
  28129. this.onAfterRenderTargetsRenderObservable.clear();
  28130. this.onAfterStepObservable.clear();
  28131. this.onBeforeStepObservable.clear();
  28132. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28133. this.onAfterActiveMeshesEvaluationObservable.clear();
  28134. this.onBeforeParticlesRenderingObservable.clear();
  28135. this.onAfterParticlesRenderingObservable.clear();
  28136. this.onBeforeSpritesRenderingObservable.clear();
  28137. this.onAfterSpritesRenderingObservable.clear();
  28138. this.onBeforeDrawPhaseObservable.clear();
  28139. this.onAfterDrawPhaseObservable.clear();
  28140. this.onBeforePhysicsObservable.clear();
  28141. this.onAfterPhysicsObservable.clear();
  28142. this.onBeforeAnimationsObservable.clear();
  28143. this.onAfterAnimationsObservable.clear();
  28144. this.onDataLoadedObservable.clear();
  28145. this.onBeforeRenderingGroupObservable.clear();
  28146. this.onAfterRenderingGroupObservable.clear();
  28147. this.detachControl();
  28148. // Release sounds & sounds tracks
  28149. if (BABYLON.AudioEngine) {
  28150. this.disposeSounds();
  28151. }
  28152. // VR Helper
  28153. if (this.VRHelper) {
  28154. this.VRHelper.dispose();
  28155. }
  28156. // Detach cameras
  28157. var canvas = this._engine.getRenderingCanvas();
  28158. if (canvas) {
  28159. var index;
  28160. for (index = 0; index < this.cameras.length; index++) {
  28161. this.cameras[index].detachControl(canvas);
  28162. }
  28163. }
  28164. // Release animation groups
  28165. while (this.animationGroups.length) {
  28166. this.animationGroups[0].dispose();
  28167. }
  28168. // Release lights
  28169. while (this.lights.length) {
  28170. this.lights[0].dispose();
  28171. }
  28172. // Release meshes
  28173. while (this.meshes.length) {
  28174. this.meshes[0].dispose(true);
  28175. }
  28176. while (this.transformNodes.length) {
  28177. this.removeTransformNode(this.transformNodes[0]);
  28178. }
  28179. // Release cameras
  28180. while (this.cameras.length) {
  28181. this.cameras[0].dispose();
  28182. }
  28183. // Release materials
  28184. if (this.defaultMaterial) {
  28185. this.defaultMaterial.dispose();
  28186. }
  28187. while (this.multiMaterials.length) {
  28188. this.multiMaterials[0].dispose();
  28189. }
  28190. while (this.materials.length) {
  28191. this.materials[0].dispose();
  28192. }
  28193. // Release particles
  28194. while (this.particleSystems.length) {
  28195. this.particleSystems[0].dispose();
  28196. }
  28197. // Release sprites
  28198. while (this.spriteManagers.length) {
  28199. this.spriteManagers[0].dispose();
  28200. }
  28201. // Release postProcesses
  28202. while (this.postProcesses.length) {
  28203. this.postProcesses[0].dispose();
  28204. }
  28205. // Release textures
  28206. while (this.textures.length) {
  28207. this.textures[0].dispose();
  28208. }
  28209. // Release UBO
  28210. this._sceneUbo.dispose();
  28211. if (this._alternateSceneUbo) {
  28212. this._alternateSceneUbo.dispose();
  28213. }
  28214. // Post-processes
  28215. this.postProcessManager.dispose();
  28216. // Physics
  28217. if (this._physicsEngine) {
  28218. this.disablePhysicsEngine();
  28219. }
  28220. // Remove from engine
  28221. index = this._engine.scenes.indexOf(this);
  28222. if (index > -1) {
  28223. this._engine.scenes.splice(index, 1);
  28224. }
  28225. this._engine.wipeCaches(true);
  28226. this._isDisposed = true;
  28227. };
  28228. Object.defineProperty(Scene.prototype, "isDisposed", {
  28229. /**
  28230. * Gets if the scene is already disposed
  28231. */
  28232. get: function () {
  28233. return this._isDisposed;
  28234. },
  28235. enumerable: true,
  28236. configurable: true
  28237. });
  28238. /**
  28239. * Releases sounds & soundtracks
  28240. */
  28241. Scene.prototype.disposeSounds = function () {
  28242. if (!this._mainSoundTrack) {
  28243. return;
  28244. }
  28245. this.mainSoundTrack.dispose();
  28246. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28247. this.soundTracks[scIndex].dispose();
  28248. }
  28249. };
  28250. /**
  28251. * Call this function to reduce memory footprint of the scene.
  28252. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28253. */
  28254. Scene.prototype.clearCachedVertexData = function () {
  28255. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28256. var mesh = this.meshes[meshIndex];
  28257. var geometry = mesh.geometry;
  28258. if (geometry) {
  28259. geometry._indices = [];
  28260. for (var vbName in geometry._vertexBuffers) {
  28261. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28262. continue;
  28263. }
  28264. geometry._vertexBuffers[vbName]._buffer._data = null;
  28265. }
  28266. }
  28267. }
  28268. };
  28269. /**
  28270. * This function will remove the local cached buffer data from texture.
  28271. * It will save memory but will prevent the texture from being rebuilt
  28272. */
  28273. Scene.prototype.cleanCachedTextureBuffer = function () {
  28274. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28275. var baseTexture = _a[_i];
  28276. var buffer = baseTexture._buffer;
  28277. if (buffer) {
  28278. baseTexture._buffer = null;
  28279. }
  28280. }
  28281. };
  28282. // Octrees
  28283. /**
  28284. * Get the world extend vectors with an optional filter
  28285. *
  28286. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28287. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28288. */
  28289. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28290. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28291. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28292. filterPredicate = filterPredicate || (function () { return true; });
  28293. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28294. mesh.computeWorldMatrix(true);
  28295. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28296. return;
  28297. }
  28298. var boundingInfo = mesh.getBoundingInfo();
  28299. var minBox = boundingInfo.boundingBox.minimumWorld;
  28300. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28301. BABYLON.Tools.CheckExtends(minBox, min, max);
  28302. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28303. });
  28304. return {
  28305. min: min,
  28306. max: max
  28307. };
  28308. };
  28309. /**
  28310. * Creates or updates the octree used to boost selection (picking)
  28311. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28312. * @param maxCapacity defines the maximum capacity per leaf
  28313. * @param maxDepth defines the maximum depth of the octree
  28314. * @returns an octree of AbstractMesh
  28315. */
  28316. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28317. if (maxCapacity === void 0) { maxCapacity = 64; }
  28318. if (maxDepth === void 0) { maxDepth = 2; }
  28319. if (!this._selectionOctree) {
  28320. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28321. }
  28322. var worldExtends = this.getWorldExtends();
  28323. // Update octree
  28324. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28325. return this._selectionOctree;
  28326. };
  28327. // Picking
  28328. /**
  28329. * Creates a ray that can be used to pick in the scene
  28330. * @param x defines the x coordinate of the origin (on-screen)
  28331. * @param y defines the y coordinate of the origin (on-screen)
  28332. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28333. * @param camera defines the camera to use for the picking
  28334. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28335. * @returns a Ray
  28336. */
  28337. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28338. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28339. var result = BABYLON.Ray.Zero();
  28340. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28341. return result;
  28342. };
  28343. /**
  28344. * Creates a ray that can be used to pick in the scene
  28345. * @param x defines the x coordinate of the origin (on-screen)
  28346. * @param y defines the y coordinate of the origin (on-screen)
  28347. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28348. * @param result defines the ray where to store the picking ray
  28349. * @param camera defines the camera to use for the picking
  28350. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28351. * @returns the current scene
  28352. */
  28353. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28354. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28355. var engine = this._engine;
  28356. if (!camera) {
  28357. if (!this.activeCamera)
  28358. throw new Error("Active camera not set");
  28359. camera = this.activeCamera;
  28360. }
  28361. var cameraViewport = camera.viewport;
  28362. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28363. // Moving coordinates to local viewport world
  28364. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28365. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28366. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28367. return this;
  28368. };
  28369. /**
  28370. * Creates a ray that can be used to pick in the scene
  28371. * @param x defines the x coordinate of the origin (on-screen)
  28372. * @param y defines the y coordinate of the origin (on-screen)
  28373. * @param camera defines the camera to use for the picking
  28374. * @returns a Ray
  28375. */
  28376. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28377. var result = BABYLON.Ray.Zero();
  28378. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28379. return result;
  28380. };
  28381. /**
  28382. * Creates a ray that can be used to pick in the scene
  28383. * @param x defines the x coordinate of the origin (on-screen)
  28384. * @param y defines the y coordinate of the origin (on-screen)
  28385. * @param result defines the ray where to store the picking ray
  28386. * @param camera defines the camera to use for the picking
  28387. * @returns the current scene
  28388. */
  28389. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28390. if (!BABYLON.PickingInfo) {
  28391. return this;
  28392. }
  28393. var engine = this._engine;
  28394. if (!camera) {
  28395. if (!this.activeCamera)
  28396. throw new Error("Active camera not set");
  28397. camera = this.activeCamera;
  28398. }
  28399. var cameraViewport = camera.viewport;
  28400. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28401. var identity = BABYLON.Matrix.Identity();
  28402. // Moving coordinates to local viewport world
  28403. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28404. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28405. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28406. return this;
  28407. };
  28408. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28409. if (!BABYLON.PickingInfo) {
  28410. return null;
  28411. }
  28412. var pickingInfo = null;
  28413. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28414. var mesh = this.meshes[meshIndex];
  28415. if (predicate) {
  28416. if (!predicate(mesh)) {
  28417. continue;
  28418. }
  28419. }
  28420. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28421. continue;
  28422. }
  28423. var world = mesh.getWorldMatrix();
  28424. var ray = rayFunction(world);
  28425. var result = mesh.intersects(ray, fastCheck);
  28426. if (!result || !result.hit)
  28427. continue;
  28428. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28429. continue;
  28430. pickingInfo = result;
  28431. if (fastCheck) {
  28432. break;
  28433. }
  28434. }
  28435. return pickingInfo || new BABYLON.PickingInfo();
  28436. };
  28437. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28438. if (!BABYLON.PickingInfo) {
  28439. return null;
  28440. }
  28441. var pickingInfos = new Array();
  28442. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28443. var mesh = this.meshes[meshIndex];
  28444. if (predicate) {
  28445. if (!predicate(mesh)) {
  28446. continue;
  28447. }
  28448. }
  28449. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28450. continue;
  28451. }
  28452. var world = mesh.getWorldMatrix();
  28453. var ray = rayFunction(world);
  28454. var result = mesh.intersects(ray, false);
  28455. if (!result || !result.hit)
  28456. continue;
  28457. pickingInfos.push(result);
  28458. }
  28459. return pickingInfos;
  28460. };
  28461. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28462. if (!BABYLON.PickingInfo) {
  28463. return null;
  28464. }
  28465. var pickingInfo = null;
  28466. if (!camera) {
  28467. if (!this.activeCamera) {
  28468. return null;
  28469. }
  28470. camera = this.activeCamera;
  28471. }
  28472. if (this.spriteManagers.length > 0) {
  28473. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28474. var spriteManager = this.spriteManagers[spriteIndex];
  28475. if (!spriteManager.isPickable) {
  28476. continue;
  28477. }
  28478. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28479. if (!result || !result.hit)
  28480. continue;
  28481. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28482. continue;
  28483. pickingInfo = result;
  28484. if (fastCheck) {
  28485. break;
  28486. }
  28487. }
  28488. }
  28489. return pickingInfo || new BABYLON.PickingInfo();
  28490. };
  28491. /** Launch a ray to try to pick a mesh in the scene
  28492. * @param x position on screen
  28493. * @param y position on screen
  28494. * @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
  28495. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28496. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28497. * @returns a PickingInfo
  28498. */
  28499. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28500. var _this = this;
  28501. if (!BABYLON.PickingInfo) {
  28502. return null;
  28503. }
  28504. var result = this._internalPick(function (world) {
  28505. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28506. return _this._tempPickingRay;
  28507. }, predicate, fastCheck);
  28508. if (result) {
  28509. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28510. }
  28511. return result;
  28512. };
  28513. /** Launch a ray to try to pick a sprite in the scene
  28514. * @param x position on screen
  28515. * @param y position on screen
  28516. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28517. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28518. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28519. * @returns a PickingInfo
  28520. */
  28521. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28522. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28523. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28524. };
  28525. /** Use the given ray to pick a mesh in the scene
  28526. * @param ray The ray to use to pick meshes
  28527. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28528. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28529. * @returns a PickingInfo
  28530. */
  28531. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28532. var _this = this;
  28533. var result = this._internalPick(function (world) {
  28534. if (!_this._pickWithRayInverseMatrix) {
  28535. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28536. }
  28537. world.invertToRef(_this._pickWithRayInverseMatrix);
  28538. if (!_this._cachedRayForTransform) {
  28539. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28540. }
  28541. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28542. return _this._cachedRayForTransform;
  28543. }, predicate, fastCheck);
  28544. if (result) {
  28545. result.ray = ray;
  28546. }
  28547. return result;
  28548. };
  28549. /**
  28550. * Launch a ray to try to pick a mesh in the scene
  28551. * @param x X position on screen
  28552. * @param y Y position on screen
  28553. * @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
  28554. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28555. * @returns an array of PickingInfo
  28556. */
  28557. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28558. var _this = this;
  28559. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28560. };
  28561. /**
  28562. * Launch a ray to try to pick a mesh in the scene
  28563. * @param ray Ray to use
  28564. * @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
  28565. * @returns an array of PickingInfo
  28566. */
  28567. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28568. var _this = this;
  28569. return this._internalMultiPick(function (world) {
  28570. if (!_this._pickWithRayInverseMatrix) {
  28571. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28572. }
  28573. world.invertToRef(_this._pickWithRayInverseMatrix);
  28574. if (!_this._cachedRayForTransform) {
  28575. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28576. }
  28577. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28578. return _this._cachedRayForTransform;
  28579. }, predicate);
  28580. };
  28581. /**
  28582. * Force the value of meshUnderPointer
  28583. * @param mesh defines the mesh to use
  28584. */
  28585. Scene.prototype.setPointerOverMesh = function (mesh) {
  28586. if (this._pointerOverMesh === mesh) {
  28587. return;
  28588. }
  28589. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28590. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28591. }
  28592. this._pointerOverMesh = mesh;
  28593. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28594. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28595. }
  28596. };
  28597. /**
  28598. * Gets the mesh under the pointer
  28599. * @returns a Mesh or null if no mesh is under the pointer
  28600. */
  28601. Scene.prototype.getPointerOverMesh = function () {
  28602. return this._pointerOverMesh;
  28603. };
  28604. /**
  28605. * Force the sprite under the pointer
  28606. * @param sprite defines the sprite to use
  28607. */
  28608. Scene.prototype.setPointerOverSprite = function (sprite) {
  28609. if (this._pointerOverSprite === sprite) {
  28610. return;
  28611. }
  28612. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28613. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28614. }
  28615. this._pointerOverSprite = sprite;
  28616. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28617. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28618. }
  28619. };
  28620. /**
  28621. * Gets the sprite under the pointer
  28622. * @returns a Sprite or null if no sprite is under the pointer
  28623. */
  28624. Scene.prototype.getPointerOverSprite = function () {
  28625. return this._pointerOverSprite;
  28626. };
  28627. // Physics
  28628. /**
  28629. * Gets the current physics engine
  28630. * @returns a PhysicsEngine or null if none attached
  28631. */
  28632. Scene.prototype.getPhysicsEngine = function () {
  28633. return this._physicsEngine;
  28634. };
  28635. /**
  28636. * Enables physics to the current scene
  28637. * @param gravity defines the scene's gravity for the physics engine
  28638. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28639. * @return a boolean indicating if the physics engine was initialized
  28640. */
  28641. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28642. if (gravity === void 0) { gravity = null; }
  28643. if (this._physicsEngine) {
  28644. return true;
  28645. }
  28646. try {
  28647. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28648. return true;
  28649. }
  28650. catch (e) {
  28651. BABYLON.Tools.Error(e.message);
  28652. return false;
  28653. }
  28654. };
  28655. /**
  28656. * Disables and disposes the physics engine associated with the scene
  28657. */
  28658. Scene.prototype.disablePhysicsEngine = function () {
  28659. if (!this._physicsEngine) {
  28660. return;
  28661. }
  28662. this._physicsEngine.dispose();
  28663. this._physicsEngine = null;
  28664. };
  28665. /**
  28666. * Gets a boolean indicating if there is an active physics engine
  28667. * @returns a boolean indicating if there is an active physics engine
  28668. */
  28669. Scene.prototype.isPhysicsEnabled = function () {
  28670. return this._physicsEngine !== undefined;
  28671. };
  28672. /**
  28673. * Deletes a physics compound impostor
  28674. * @param compound defines the compound to delete
  28675. */
  28676. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28677. var mesh = compound.parts[0].mesh;
  28678. if (mesh.physicsImpostor) {
  28679. mesh.physicsImpostor.dispose( /*true*/);
  28680. mesh.physicsImpostor = null;
  28681. }
  28682. };
  28683. // Misc.
  28684. /** @hidden */
  28685. Scene.prototype._rebuildGeometries = function () {
  28686. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28687. var geometry = _a[_i];
  28688. geometry._rebuild();
  28689. }
  28690. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28691. var mesh = _c[_b];
  28692. mesh._rebuild();
  28693. }
  28694. if (this.postProcessManager) {
  28695. this.postProcessManager._rebuild();
  28696. }
  28697. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28698. var component = _e[_d];
  28699. component.rebuild();
  28700. }
  28701. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28702. var system = _g[_f];
  28703. system.rebuild();
  28704. }
  28705. for (var _h = 0, _j = this._rebuildGeometryStage; _h < _j.length; _h++) {
  28706. var step = _j[_h];
  28707. step.action();
  28708. }
  28709. };
  28710. /** @hidden */
  28711. Scene.prototype._rebuildTextures = function () {
  28712. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28713. var texture = _a[_i];
  28714. texture._rebuild();
  28715. }
  28716. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28717. };
  28718. /**
  28719. * Creates a default light for the scene.
  28720. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28721. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28722. */
  28723. Scene.prototype.createDefaultLight = function (replace) {
  28724. if (replace === void 0) { replace = false; }
  28725. // Dispose existing light in replace mode.
  28726. if (replace) {
  28727. if (this.lights) {
  28728. for (var i = 0; i < this.lights.length; i++) {
  28729. this.lights[i].dispose();
  28730. }
  28731. }
  28732. }
  28733. // Light
  28734. if (this.lights.length === 0) {
  28735. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28736. }
  28737. };
  28738. /**
  28739. * Creates a default camera for the scene.
  28740. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28741. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28742. * @param replace has default false, when true replaces the active camera in the scene
  28743. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28744. */
  28745. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28746. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28747. if (replace === void 0) { replace = false; }
  28748. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28749. // Dispose existing camera in replace mode.
  28750. if (replace) {
  28751. if (this.activeCamera) {
  28752. this.activeCamera.dispose();
  28753. this.activeCamera = null;
  28754. }
  28755. }
  28756. // Camera
  28757. if (!this.activeCamera) {
  28758. var worldExtends = this.getWorldExtends();
  28759. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28760. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28761. var camera;
  28762. var radius = worldSize.length() * 1.5;
  28763. // empty scene scenario!
  28764. if (!isFinite(radius)) {
  28765. radius = 1;
  28766. worldCenter.copyFromFloats(0, 0, 0);
  28767. }
  28768. if (createArcRotateCamera) {
  28769. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28770. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28771. arcRotateCamera.wheelPrecision = 100 / radius;
  28772. camera = arcRotateCamera;
  28773. }
  28774. else {
  28775. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28776. freeCamera.setTarget(worldCenter);
  28777. camera = freeCamera;
  28778. }
  28779. camera.minZ = radius * 0.01;
  28780. camera.maxZ = radius * 1000;
  28781. camera.speed = radius * 0.2;
  28782. this.activeCamera = camera;
  28783. var canvas = this.getEngine().getRenderingCanvas();
  28784. if (attachCameraControls && canvas) {
  28785. camera.attachControl(canvas);
  28786. }
  28787. }
  28788. };
  28789. /**
  28790. * Creates a default camera and a default light.
  28791. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28792. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28793. * @param replace has the default false, when true replaces the active camera/light in the scene
  28794. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28795. */
  28796. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28797. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28798. if (replace === void 0) { replace = false; }
  28799. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28800. this.createDefaultLight(replace);
  28801. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28802. };
  28803. /**
  28804. * Creates a new sky box
  28805. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28806. * @param environmentTexture defines the texture to use as environment texture
  28807. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28808. * @param scale defines the overall scale of the skybox
  28809. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28810. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28811. * @returns a new mesh holding the sky box
  28812. */
  28813. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28814. if (pbr === void 0) { pbr = false; }
  28815. if (scale === void 0) { scale = 1000; }
  28816. if (blur === void 0) { blur = 0; }
  28817. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28818. if (!environmentTexture) {
  28819. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28820. return null;
  28821. }
  28822. if (setGlobalEnvTexture) {
  28823. if (environmentTexture) {
  28824. this.environmentTexture = environmentTexture;
  28825. }
  28826. }
  28827. // Skybox
  28828. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28829. if (pbr) {
  28830. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28831. hdrSkyboxMaterial.backFaceCulling = false;
  28832. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28833. if (hdrSkyboxMaterial.reflectionTexture) {
  28834. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28835. }
  28836. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28837. hdrSkyboxMaterial.disableLighting = true;
  28838. hdrSkyboxMaterial.twoSidedLighting = true;
  28839. hdrSkybox.infiniteDistance = true;
  28840. hdrSkybox.material = hdrSkyboxMaterial;
  28841. }
  28842. else {
  28843. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28844. skyboxMaterial.backFaceCulling = false;
  28845. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28846. if (skyboxMaterial.reflectionTexture) {
  28847. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28848. }
  28849. skyboxMaterial.disableLighting = true;
  28850. hdrSkybox.infiniteDistance = true;
  28851. hdrSkybox.material = skyboxMaterial;
  28852. }
  28853. return hdrSkybox;
  28854. };
  28855. /**
  28856. * Creates a new environment
  28857. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28858. * @param options defines the options you can use to configure the environment
  28859. * @returns the new EnvironmentHelper
  28860. */
  28861. Scene.prototype.createDefaultEnvironment = function (options) {
  28862. if (BABYLON.EnvironmentHelper) {
  28863. return new BABYLON.EnvironmentHelper(options, this);
  28864. }
  28865. return null;
  28866. };
  28867. /**
  28868. * Creates a new VREXperienceHelper
  28869. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28870. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28871. * @returns a new VREXperienceHelper
  28872. */
  28873. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28874. if (webVROptions === void 0) { webVROptions = {}; }
  28875. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28876. };
  28877. // Tags
  28878. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28879. if (tagsQuery === undefined) {
  28880. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28881. return list;
  28882. }
  28883. var listByTags = [];
  28884. forEach = forEach || (function (item) { return; });
  28885. for (var i in list) {
  28886. var item = list[i];
  28887. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28888. listByTags.push(item);
  28889. forEach(item);
  28890. }
  28891. }
  28892. return listByTags;
  28893. };
  28894. /**
  28895. * Get a list of meshes by tags
  28896. * @param tagsQuery defines the tags query to use
  28897. * @param forEach defines a predicate used to filter results
  28898. * @returns an array of Mesh
  28899. */
  28900. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28901. return this._getByTags(this.meshes, tagsQuery, forEach);
  28902. };
  28903. /**
  28904. * Get a list of cameras by tags
  28905. * @param tagsQuery defines the tags query to use
  28906. * @param forEach defines a predicate used to filter results
  28907. * @returns an array of Camera
  28908. */
  28909. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28910. return this._getByTags(this.cameras, tagsQuery, forEach);
  28911. };
  28912. /**
  28913. * Get a list of lights by tags
  28914. * @param tagsQuery defines the tags query to use
  28915. * @param forEach defines a predicate used to filter results
  28916. * @returns an array of Light
  28917. */
  28918. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28919. return this._getByTags(this.lights, tagsQuery, forEach);
  28920. };
  28921. /**
  28922. * Get a list of materials by tags
  28923. * @param tagsQuery defines the tags query to use
  28924. * @param forEach defines a predicate used to filter results
  28925. * @returns an array of Material
  28926. */
  28927. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28928. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28929. };
  28930. /**
  28931. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28932. * This allowed control for front to back rendering or reversly depending of the special needs.
  28933. *
  28934. * @param renderingGroupId The rendering group id corresponding to its index
  28935. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28936. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28937. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28938. */
  28939. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28940. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28941. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28942. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28943. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28944. };
  28945. /**
  28946. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28947. *
  28948. * @param renderingGroupId The rendering group id corresponding to its index
  28949. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28950. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28951. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28952. */
  28953. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28954. if (depth === void 0) { depth = true; }
  28955. if (stencil === void 0) { stencil = true; }
  28956. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28957. };
  28958. /**
  28959. * Gets the current auto clear configuration for one rendering group of the rendering
  28960. * manager.
  28961. * @param index the rendering group index to get the information for
  28962. * @returns The auto clear setup for the requested rendering group
  28963. */
  28964. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28965. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28966. };
  28967. /**
  28968. * Will flag all materials as dirty to trigger new shader compilation
  28969. * @param flag defines the flag used to specify which material part must be marked as dirty
  28970. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28971. */
  28972. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28973. if (this.blockMaterialDirtyMechanism) {
  28974. return;
  28975. }
  28976. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28977. var material = _a[_i];
  28978. if (predicate && !predicate(material)) {
  28979. continue;
  28980. }
  28981. material.markAsDirty(flag);
  28982. }
  28983. };
  28984. /** @hidden */
  28985. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28986. var _this = this;
  28987. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28988. this._activeRequests.push(request);
  28989. request.onCompleteObservable.add(function (request) {
  28990. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28991. });
  28992. return request;
  28993. };
  28994. /** @hidden */
  28995. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28996. var _this = this;
  28997. return new Promise(function (resolve, reject) {
  28998. _this._loadFile(url, function (data) {
  28999. resolve(data);
  29000. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29001. reject(exception);
  29002. });
  29003. });
  29004. };
  29005. // Statics
  29006. Scene._uniqueIdCounter = 0;
  29007. /** The fog is deactivated */
  29008. Scene.FOGMODE_NONE = 0;
  29009. /** The fog density is following an exponential function */
  29010. Scene.FOGMODE_EXP = 1;
  29011. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29012. Scene.FOGMODE_EXP2 = 2;
  29013. /** The fog density is following a linear function. */
  29014. Scene.FOGMODE_LINEAR = 3;
  29015. /**
  29016. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29017. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29018. */
  29019. Scene.MinDeltaTime = 1.0;
  29020. /**
  29021. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29022. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29023. */
  29024. Scene.MaxDeltaTime = 1000.0;
  29025. /** The distance in pixel that you have to move to prevent some events */
  29026. Scene.DragMovementThreshold = 10; // in pixels
  29027. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29028. Scene.LongPressDelay = 500; // in milliseconds
  29029. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29030. Scene.DoubleClickDelay = 300; // in milliseconds
  29031. /** If you need to check double click without raising a single click at first click, enable this flag */
  29032. Scene.ExclusiveDoubleClickMode = false;
  29033. return Scene;
  29034. }(BABYLON.AbstractScene));
  29035. BABYLON.Scene = Scene;
  29036. })(BABYLON || (BABYLON = {}));
  29037. //# sourceMappingURL=babylon.scene.js.map
  29038. var BABYLON;
  29039. (function (BABYLON) {
  29040. /**
  29041. * Set of assets to keep when moving a scene into an asset container.
  29042. */
  29043. var KeepAssets = /** @class */ (function (_super) {
  29044. __extends(KeepAssets, _super);
  29045. function KeepAssets() {
  29046. return _super !== null && _super.apply(this, arguments) || this;
  29047. }
  29048. return KeepAssets;
  29049. }(BABYLON.AbstractScene));
  29050. BABYLON.KeepAssets = KeepAssets;
  29051. /**
  29052. * Container with a set of assets that can be added or removed from a scene.
  29053. */
  29054. var AssetContainer = /** @class */ (function (_super) {
  29055. __extends(AssetContainer, _super);
  29056. /**
  29057. * Instantiates an AssetContainer.
  29058. * @param scene The scene the AssetContainer belongs to.
  29059. */
  29060. function AssetContainer(scene) {
  29061. var _this = _super.call(this) || this;
  29062. _this.scene = scene;
  29063. return _this;
  29064. }
  29065. /**
  29066. * Adds all the assets from the container to the scene.
  29067. */
  29068. AssetContainer.prototype.addAllToScene = function () {
  29069. var _this = this;
  29070. this.cameras.forEach(function (o) {
  29071. _this.scene.addCamera(o);
  29072. });
  29073. this.lights.forEach(function (o) {
  29074. _this.scene.addLight(o);
  29075. });
  29076. this.meshes.forEach(function (o) {
  29077. _this.scene.addMesh(o);
  29078. });
  29079. this.skeletons.forEach(function (o) {
  29080. _this.scene.addSkeleton(o);
  29081. });
  29082. this.animations.forEach(function (o) {
  29083. _this.scene.addAnimation(o);
  29084. });
  29085. this.animationGroups.forEach(function (o) {
  29086. _this.scene.addAnimationGroup(o);
  29087. });
  29088. this.multiMaterials.forEach(function (o) {
  29089. _this.scene.addMultiMaterial(o);
  29090. });
  29091. this.materials.forEach(function (o) {
  29092. _this.scene.addMaterial(o);
  29093. });
  29094. this.morphTargetManagers.forEach(function (o) {
  29095. _this.scene.addMorphTargetManager(o);
  29096. });
  29097. this.geometries.forEach(function (o) {
  29098. _this.scene.addGeometry(o);
  29099. });
  29100. this.transformNodes.forEach(function (o) {
  29101. _this.scene.addTransformNode(o);
  29102. });
  29103. this.actionManagers.forEach(function (o) {
  29104. _this.scene.addActionManager(o);
  29105. });
  29106. this.sounds.forEach(function (o) {
  29107. o.play();
  29108. o.autoplay = true;
  29109. _this.scene.mainSoundTrack.AddSound(o);
  29110. });
  29111. this.textures.forEach(function (o) {
  29112. _this.scene.addTexture(o);
  29113. });
  29114. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29115. var component = _a[_i];
  29116. component.addFromContainer(this.scene);
  29117. }
  29118. };
  29119. /**
  29120. * Removes all the assets in the container from the scene
  29121. */
  29122. AssetContainer.prototype.removeAllFromScene = function () {
  29123. var _this = this;
  29124. this.cameras.forEach(function (o) {
  29125. _this.scene.removeCamera(o);
  29126. });
  29127. this.lights.forEach(function (o) {
  29128. _this.scene.removeLight(o);
  29129. });
  29130. this.meshes.forEach(function (o) {
  29131. _this.scene.removeMesh(o);
  29132. });
  29133. this.skeletons.forEach(function (o) {
  29134. _this.scene.removeSkeleton(o);
  29135. });
  29136. this.animations.forEach(function (o) {
  29137. _this.scene.removeAnimation(o);
  29138. });
  29139. this.animationGroups.forEach(function (o) {
  29140. _this.scene.removeAnimationGroup(o);
  29141. });
  29142. this.multiMaterials.forEach(function (o) {
  29143. _this.scene.removeMultiMaterial(o);
  29144. });
  29145. this.materials.forEach(function (o) {
  29146. _this.scene.removeMaterial(o);
  29147. });
  29148. this.morphTargetManagers.forEach(function (o) {
  29149. _this.scene.removeMorphTargetManager(o);
  29150. });
  29151. this.geometries.forEach(function (o) {
  29152. _this.scene.removeGeometry(o);
  29153. });
  29154. this.transformNodes.forEach(function (o) {
  29155. _this.scene.removeTransformNode(o);
  29156. });
  29157. this.actionManagers.forEach(function (o) {
  29158. _this.scene.removeActionManager(o);
  29159. });
  29160. this.sounds.forEach(function (o) {
  29161. o.stop();
  29162. o.autoplay = false;
  29163. _this.scene.mainSoundTrack.RemoveSound(o);
  29164. });
  29165. this.textures.forEach(function (o) {
  29166. _this.scene.removeTexture(o);
  29167. });
  29168. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29169. var component = _a[_i];
  29170. component.removeFromContainer(this.scene);
  29171. }
  29172. };
  29173. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29174. if (!sourceAssets) {
  29175. return;
  29176. }
  29177. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29178. var asset = sourceAssets_1[_i];
  29179. var move = true;
  29180. if (keepAssets) {
  29181. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29182. var keepAsset = keepAssets_1[_a];
  29183. if (asset === keepAsset) {
  29184. move = false;
  29185. break;
  29186. }
  29187. }
  29188. }
  29189. if (move) {
  29190. targetAssets.push(asset);
  29191. }
  29192. }
  29193. };
  29194. /**
  29195. * Removes all the assets contained in the scene and adds them to the container.
  29196. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29197. */
  29198. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29199. if (keepAssets === undefined) {
  29200. keepAssets = new KeepAssets();
  29201. }
  29202. for (var key in this) {
  29203. if (this.hasOwnProperty(key)) {
  29204. this[key] = this[key] || [];
  29205. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29206. }
  29207. }
  29208. this.removeAllFromScene();
  29209. };
  29210. /**
  29211. * 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.
  29212. * @returns the root mesh
  29213. */
  29214. AssetContainer.prototype.createRootMesh = function () {
  29215. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29216. this.meshes.forEach(function (m) {
  29217. if (!m.parent) {
  29218. rootMesh.addChild(m);
  29219. }
  29220. });
  29221. this.meshes.unshift(rootMesh);
  29222. return rootMesh;
  29223. };
  29224. return AssetContainer;
  29225. }(BABYLON.AbstractScene));
  29226. BABYLON.AssetContainer = AssetContainer;
  29227. })(BABYLON || (BABYLON = {}));
  29228. //# sourceMappingURL=babylon.assetContainer.js.map
  29229. var BABYLON;
  29230. (function (BABYLON) {
  29231. var Buffer = /** @class */ (function () {
  29232. /**
  29233. * Constructor
  29234. * @param engine the engine
  29235. * @param data the data to use for this buffer
  29236. * @param updatable whether the data is updatable
  29237. * @param stride the stride (optional)
  29238. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29239. * @param instanced whether the buffer is instanced (optional)
  29240. * @param useBytes set to true if the stride in in bytes (optional)
  29241. */
  29242. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29243. if (stride === void 0) { stride = 0; }
  29244. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29245. if (instanced === void 0) { instanced = false; }
  29246. if (useBytes === void 0) { useBytes = false; }
  29247. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29248. this._engine = engine.getScene().getEngine();
  29249. }
  29250. else {
  29251. this._engine = engine;
  29252. }
  29253. this._updatable = updatable;
  29254. this._instanced = instanced;
  29255. this._data = data;
  29256. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29257. if (!postponeInternalCreation) { // by default
  29258. this.create();
  29259. }
  29260. }
  29261. /**
  29262. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29263. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29264. * @param offset defines offset in the buffer (0 by default)
  29265. * @param size defines the size in floats of attributes (position is 3 for instance)
  29266. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29267. * @param instanced defines if the vertex buffer contains indexed data
  29268. * @param useBytes defines if the offset and stride are in bytes
  29269. * @returns the new vertex buffer
  29270. */
  29271. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29272. if (useBytes === void 0) { useBytes = false; }
  29273. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29274. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29275. // a lot of these parameters are ignored as they are overriden by the buffer
  29276. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29277. };
  29278. // Properties
  29279. Buffer.prototype.isUpdatable = function () {
  29280. return this._updatable;
  29281. };
  29282. Buffer.prototype.getData = function () {
  29283. return this._data;
  29284. };
  29285. Buffer.prototype.getBuffer = function () {
  29286. return this._buffer;
  29287. };
  29288. /**
  29289. * Gets the stride in float32 units (i.e. byte stride / 4).
  29290. * May not be an integer if the byte stride is not divisible by 4.
  29291. * DEPRECATED. Use byteStride instead.
  29292. * @returns the stride in float32 units
  29293. */
  29294. Buffer.prototype.getStrideSize = function () {
  29295. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29296. };
  29297. // Methods
  29298. Buffer.prototype.create = function (data) {
  29299. if (data === void 0) { data = null; }
  29300. if (!data && this._buffer) {
  29301. return; // nothing to do
  29302. }
  29303. data = data || this._data;
  29304. if (!data) {
  29305. return;
  29306. }
  29307. if (!this._buffer) { // create buffer
  29308. if (this._updatable) {
  29309. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29310. this._data = data;
  29311. }
  29312. else {
  29313. this._buffer = this._engine.createVertexBuffer(data);
  29314. }
  29315. }
  29316. else if (this._updatable) { // update buffer
  29317. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29318. this._data = data;
  29319. }
  29320. };
  29321. /** @hidden */
  29322. Buffer.prototype._rebuild = function () {
  29323. this._buffer = null;
  29324. this.create(this._data);
  29325. };
  29326. Buffer.prototype.update = function (data) {
  29327. this.create(data);
  29328. };
  29329. /**
  29330. * Updates the data directly.
  29331. * @param data the new data
  29332. * @param offset the new offset
  29333. * @param vertexCount the vertex count (optional)
  29334. * @param useBytes set to true if the offset is in bytes
  29335. */
  29336. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29337. if (useBytes === void 0) { useBytes = false; }
  29338. if (!this._buffer) {
  29339. return;
  29340. }
  29341. if (this._updatable) { // update buffer
  29342. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29343. this._data = null;
  29344. }
  29345. };
  29346. Buffer.prototype.dispose = function () {
  29347. if (!this._buffer) {
  29348. return;
  29349. }
  29350. if (this._engine._releaseBuffer(this._buffer)) {
  29351. this._buffer = null;
  29352. }
  29353. };
  29354. return Buffer;
  29355. }());
  29356. BABYLON.Buffer = Buffer;
  29357. })(BABYLON || (BABYLON = {}));
  29358. //# sourceMappingURL=babylon.buffer.js.map
  29359. var BABYLON;
  29360. (function (BABYLON) {
  29361. var VertexBuffer = /** @class */ (function () {
  29362. /**
  29363. * Constructor
  29364. * @param engine the engine
  29365. * @param data the data to use for this vertex buffer
  29366. * @param kind the vertex buffer kind
  29367. * @param updatable whether the data is updatable
  29368. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29369. * @param stride the stride (optional)
  29370. * @param instanced whether the buffer is instanced (optional)
  29371. * @param offset the offset of the data (optional)
  29372. * @param size the number of components (optional)
  29373. * @param type the type of the component (optional)
  29374. * @param normalized whether the data contains normalized data (optional)
  29375. * @param useBytes set to true if stride and offset are in bytes (optional)
  29376. */
  29377. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29378. if (normalized === void 0) { normalized = false; }
  29379. if (useBytes === void 0) { useBytes = false; }
  29380. if (data instanceof BABYLON.Buffer) {
  29381. this._buffer = data;
  29382. this._ownsBuffer = false;
  29383. }
  29384. else {
  29385. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29386. this._ownsBuffer = true;
  29387. }
  29388. this._kind = kind;
  29389. if (type == undefined) {
  29390. var data_1 = this.getData();
  29391. this.type = VertexBuffer.FLOAT;
  29392. if (data_1 instanceof Int8Array)
  29393. this.type = VertexBuffer.BYTE;
  29394. else if (data_1 instanceof Uint8Array)
  29395. this.type = VertexBuffer.UNSIGNED_BYTE;
  29396. else if (data_1 instanceof Int16Array)
  29397. this.type = VertexBuffer.SHORT;
  29398. else if (data_1 instanceof Uint16Array)
  29399. this.type = VertexBuffer.UNSIGNED_SHORT;
  29400. else if (data_1 instanceof Int32Array)
  29401. this.type = VertexBuffer.INT;
  29402. else if (data_1 instanceof Uint32Array)
  29403. this.type = VertexBuffer.UNSIGNED_INT;
  29404. }
  29405. else {
  29406. this.type = type;
  29407. }
  29408. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29409. if (useBytes) {
  29410. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29411. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29412. this.byteOffset = offset || 0;
  29413. }
  29414. else {
  29415. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29416. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29417. this.byteOffset = (offset || 0) * typeByteLength;
  29418. }
  29419. this.normalized = normalized;
  29420. this._instanced = instanced !== undefined ? instanced : false;
  29421. this._instanceDivisor = instanced ? 1 : 0;
  29422. }
  29423. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29424. /**
  29425. * Gets or sets the instance divisor when in instanced mode
  29426. */
  29427. get: function () {
  29428. return this._instanceDivisor;
  29429. },
  29430. set: function (value) {
  29431. this._instanceDivisor = value;
  29432. if (value == 0) {
  29433. this._instanced = false;
  29434. }
  29435. else {
  29436. this._instanced = true;
  29437. }
  29438. },
  29439. enumerable: true,
  29440. configurable: true
  29441. });
  29442. /** @hidden */
  29443. VertexBuffer.prototype._rebuild = function () {
  29444. if (!this._buffer) {
  29445. return;
  29446. }
  29447. this._buffer._rebuild();
  29448. };
  29449. /**
  29450. * Returns the kind of the VertexBuffer (string).
  29451. */
  29452. VertexBuffer.prototype.getKind = function () {
  29453. return this._kind;
  29454. };
  29455. // Properties
  29456. /**
  29457. * Boolean : is the VertexBuffer updatable ?
  29458. */
  29459. VertexBuffer.prototype.isUpdatable = function () {
  29460. return this._buffer.isUpdatable();
  29461. };
  29462. /**
  29463. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29464. */
  29465. VertexBuffer.prototype.getData = function () {
  29466. return this._buffer.getData();
  29467. };
  29468. /**
  29469. * Returns the WebGLBuffer associated to the VertexBuffer.
  29470. */
  29471. VertexBuffer.prototype.getBuffer = function () {
  29472. return this._buffer.getBuffer();
  29473. };
  29474. /**
  29475. * Returns the stride as a multiple of the type byte length.
  29476. * DEPRECATED. Use byteStride instead.
  29477. */
  29478. VertexBuffer.prototype.getStrideSize = function () {
  29479. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29480. };
  29481. /**
  29482. * Returns the offset as a multiple of the type byte length.
  29483. * DEPRECATED. Use byteOffset instead.
  29484. */
  29485. VertexBuffer.prototype.getOffset = function () {
  29486. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29487. };
  29488. /**
  29489. * Returns the number of components per vertex attribute (integer).
  29490. */
  29491. VertexBuffer.prototype.getSize = function () {
  29492. return this._size;
  29493. };
  29494. /**
  29495. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29496. */
  29497. VertexBuffer.prototype.getIsInstanced = function () {
  29498. return this._instanced;
  29499. };
  29500. /**
  29501. * Returns the instancing divisor, zero for non-instanced (integer).
  29502. */
  29503. VertexBuffer.prototype.getInstanceDivisor = function () {
  29504. return this._instanceDivisor;
  29505. };
  29506. // Methods
  29507. /**
  29508. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29509. * Returns the created WebGLBuffer.
  29510. */
  29511. VertexBuffer.prototype.create = function (data) {
  29512. return this._buffer.create(data);
  29513. };
  29514. /**
  29515. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29516. * This function will create a new buffer if the current one is not updatable
  29517. * Returns the updated WebGLBuffer.
  29518. */
  29519. VertexBuffer.prototype.update = function (data) {
  29520. return this._buffer.update(data);
  29521. };
  29522. /**
  29523. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29524. * Returns the directly updated WebGLBuffer.
  29525. * @param data the new data
  29526. * @param offset the new offset
  29527. * @param useBytes set to true if the offset is in bytes
  29528. */
  29529. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29530. if (useBytes === void 0) { useBytes = false; }
  29531. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29532. };
  29533. /**
  29534. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29535. */
  29536. VertexBuffer.prototype.dispose = function () {
  29537. if (this._ownsBuffer) {
  29538. this._buffer.dispose();
  29539. }
  29540. };
  29541. /**
  29542. * Enumerates each value of this vertex buffer as numbers.
  29543. * @param count the number of values to enumerate
  29544. * @param callback the callback function called for each value
  29545. */
  29546. VertexBuffer.prototype.forEach = function (count, callback) {
  29547. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29548. };
  29549. Object.defineProperty(VertexBuffer, "PositionKind", {
  29550. get: function () {
  29551. return VertexBuffer._PositionKind;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. Object.defineProperty(VertexBuffer, "NormalKind", {
  29557. get: function () {
  29558. return VertexBuffer._NormalKind;
  29559. },
  29560. enumerable: true,
  29561. configurable: true
  29562. });
  29563. Object.defineProperty(VertexBuffer, "TangentKind", {
  29564. get: function () {
  29565. return VertexBuffer._TangentKind;
  29566. },
  29567. enumerable: true,
  29568. configurable: true
  29569. });
  29570. Object.defineProperty(VertexBuffer, "UVKind", {
  29571. get: function () {
  29572. return VertexBuffer._UVKind;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29578. get: function () {
  29579. return VertexBuffer._UV2Kind;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29585. get: function () {
  29586. return VertexBuffer._UV3Kind;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29592. get: function () {
  29593. return VertexBuffer._UV4Kind;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29599. get: function () {
  29600. return VertexBuffer._UV5Kind;
  29601. },
  29602. enumerable: true,
  29603. configurable: true
  29604. });
  29605. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29606. get: function () {
  29607. return VertexBuffer._UV6Kind;
  29608. },
  29609. enumerable: true,
  29610. configurable: true
  29611. });
  29612. Object.defineProperty(VertexBuffer, "ColorKind", {
  29613. get: function () {
  29614. return VertexBuffer._ColorKind;
  29615. },
  29616. enumerable: true,
  29617. configurable: true
  29618. });
  29619. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29620. get: function () {
  29621. return VertexBuffer._MatricesIndicesKind;
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29627. get: function () {
  29628. return VertexBuffer._MatricesWeightsKind;
  29629. },
  29630. enumerable: true,
  29631. configurable: true
  29632. });
  29633. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29634. get: function () {
  29635. return VertexBuffer._MatricesIndicesExtraKind;
  29636. },
  29637. enumerable: true,
  29638. configurable: true
  29639. });
  29640. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29641. get: function () {
  29642. return VertexBuffer._MatricesWeightsExtraKind;
  29643. },
  29644. enumerable: true,
  29645. configurable: true
  29646. });
  29647. /**
  29648. * Deduces the stride given a kind.
  29649. * @param kind The kind string to deduce
  29650. * @returns The deduced stride
  29651. */
  29652. VertexBuffer.DeduceStride = function (kind) {
  29653. switch (kind) {
  29654. case VertexBuffer.UVKind:
  29655. case VertexBuffer.UV2Kind:
  29656. case VertexBuffer.UV3Kind:
  29657. case VertexBuffer.UV4Kind:
  29658. case VertexBuffer.UV5Kind:
  29659. case VertexBuffer.UV6Kind:
  29660. return 2;
  29661. case VertexBuffer.NormalKind:
  29662. case VertexBuffer.PositionKind:
  29663. return 3;
  29664. case VertexBuffer.ColorKind:
  29665. case VertexBuffer.MatricesIndicesKind:
  29666. case VertexBuffer.MatricesIndicesExtraKind:
  29667. case VertexBuffer.MatricesWeightsKind:
  29668. case VertexBuffer.MatricesWeightsExtraKind:
  29669. case VertexBuffer.TangentKind:
  29670. return 4;
  29671. default:
  29672. throw new Error("Invalid kind '" + kind + "'");
  29673. }
  29674. };
  29675. /**
  29676. * Gets the byte length of the given type.
  29677. * @param type the type
  29678. * @returns the number of bytes
  29679. */
  29680. VertexBuffer.GetTypeByteLength = function (type) {
  29681. switch (type) {
  29682. case VertexBuffer.BYTE:
  29683. case VertexBuffer.UNSIGNED_BYTE:
  29684. return 1;
  29685. case VertexBuffer.SHORT:
  29686. case VertexBuffer.UNSIGNED_SHORT:
  29687. return 2;
  29688. case VertexBuffer.INT:
  29689. case VertexBuffer.FLOAT:
  29690. return 4;
  29691. default:
  29692. throw new Error("Invalid type '" + type + "'");
  29693. }
  29694. };
  29695. /**
  29696. * Enumerates each value of the given parameters as numbers.
  29697. * @param data the data to enumerate
  29698. * @param byteOffset the byte offset of the data
  29699. * @param byteStride the byte stride of the data
  29700. * @param componentCount the number of components per element
  29701. * @param componentType the type of the component
  29702. * @param count the total number of components
  29703. * @param normalized whether the data is normalized
  29704. * @param callback the callback function called for each value
  29705. */
  29706. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29707. if (data instanceof Array) {
  29708. var offset = byteOffset / 4;
  29709. var stride = byteStride / 4;
  29710. for (var index = 0; index < count; index += componentCount) {
  29711. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29712. callback(data[offset + componentIndex], index + componentIndex);
  29713. }
  29714. offset += stride;
  29715. }
  29716. }
  29717. else {
  29718. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29719. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29720. for (var index = 0; index < count; index += componentCount) {
  29721. var componentByteOffset = byteOffset;
  29722. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29723. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29724. callback(value, index + componentIndex);
  29725. componentByteOffset += componentByteLength;
  29726. }
  29727. byteOffset += byteStride;
  29728. }
  29729. }
  29730. };
  29731. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29732. switch (type) {
  29733. case VertexBuffer.BYTE: {
  29734. var value = dataView.getInt8(byteOffset);
  29735. if (normalized) {
  29736. value = Math.max(value / 127, -1);
  29737. }
  29738. return value;
  29739. }
  29740. case VertexBuffer.UNSIGNED_BYTE: {
  29741. var value = dataView.getUint8(byteOffset);
  29742. if (normalized) {
  29743. value = value / 255;
  29744. }
  29745. return value;
  29746. }
  29747. case VertexBuffer.SHORT: {
  29748. var value = dataView.getInt16(byteOffset, true);
  29749. if (normalized) {
  29750. value = Math.max(value / 16383, -1);
  29751. }
  29752. return value;
  29753. }
  29754. case VertexBuffer.UNSIGNED_SHORT: {
  29755. var value = dataView.getUint16(byteOffset, true);
  29756. if (normalized) {
  29757. value = value / 65535;
  29758. }
  29759. return value;
  29760. }
  29761. case VertexBuffer.FLOAT: {
  29762. return dataView.getFloat32(byteOffset, true);
  29763. }
  29764. default: {
  29765. throw new Error("Invalid component type " + type);
  29766. }
  29767. }
  29768. };
  29769. /**
  29770. * The byte type.
  29771. */
  29772. VertexBuffer.BYTE = 5120;
  29773. /**
  29774. * The unsigned byte type.
  29775. */
  29776. VertexBuffer.UNSIGNED_BYTE = 5121;
  29777. /**
  29778. * The short type.
  29779. */
  29780. VertexBuffer.SHORT = 5122;
  29781. /**
  29782. * The unsigned short type.
  29783. */
  29784. VertexBuffer.UNSIGNED_SHORT = 5123;
  29785. /**
  29786. * The integer type.
  29787. */
  29788. VertexBuffer.INT = 5124;
  29789. /**
  29790. * The unsigned integer type.
  29791. */
  29792. VertexBuffer.UNSIGNED_INT = 5125;
  29793. /**
  29794. * The float type.
  29795. */
  29796. VertexBuffer.FLOAT = 5126;
  29797. // Enums
  29798. VertexBuffer._PositionKind = "position";
  29799. VertexBuffer._NormalKind = "normal";
  29800. VertexBuffer._TangentKind = "tangent";
  29801. VertexBuffer._UVKind = "uv";
  29802. VertexBuffer._UV2Kind = "uv2";
  29803. VertexBuffer._UV3Kind = "uv3";
  29804. VertexBuffer._UV4Kind = "uv4";
  29805. VertexBuffer._UV5Kind = "uv5";
  29806. VertexBuffer._UV6Kind = "uv6";
  29807. VertexBuffer._ColorKind = "color";
  29808. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29809. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29810. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29811. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29812. return VertexBuffer;
  29813. }());
  29814. BABYLON.VertexBuffer = VertexBuffer;
  29815. })(BABYLON || (BABYLON = {}));
  29816. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29817. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29818. var BABYLON;
  29819. (function (BABYLON) {
  29820. /**
  29821. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29822. */
  29823. var DummyInternalTextureTracker = /** @class */ (function () {
  29824. function DummyInternalTextureTracker() {
  29825. /**
  29826. * Gets or set the previous tracker in the list
  29827. */
  29828. this.previous = null;
  29829. /**
  29830. * Gets or set the next tracker in the list
  29831. */
  29832. this.next = null;
  29833. }
  29834. return DummyInternalTextureTracker;
  29835. }());
  29836. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29837. })(BABYLON || (BABYLON = {}));
  29838. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29839. var BABYLON;
  29840. (function (BABYLON) {
  29841. /**
  29842. * Class used to store data associated with WebGL texture data for the engine
  29843. * This class should not be used directly
  29844. */
  29845. var InternalTexture = /** @class */ (function () {
  29846. /**
  29847. * Creates a new InternalTexture
  29848. * @param engine defines the engine to use
  29849. * @param dataSource defines the type of data that will be used
  29850. */
  29851. function InternalTexture(engine, dataSource) {
  29852. /**
  29853. * Observable called when the texture is loaded
  29854. */
  29855. this.onLoadedObservable = new BABYLON.Observable();
  29856. /**
  29857. * Gets or set the previous tracker in the list
  29858. */
  29859. this.previous = null;
  29860. /**
  29861. * Gets or set the next tracker in the list
  29862. */
  29863. this.next = null;
  29864. // Private
  29865. /** @hidden */
  29866. this._initialSlot = -1;
  29867. /** @hidden */
  29868. this._designatedSlot = -1;
  29869. /** @hidden */
  29870. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29871. /** @hidden */
  29872. this._comparisonFunction = 0;
  29873. /** @hidden */
  29874. this._sphericalPolynomial = null;
  29875. /** @hidden */
  29876. this._lodGenerationScale = 0;
  29877. /** @hidden */
  29878. this._lodGenerationOffset = 0;
  29879. /** @hidden */
  29880. this._isRGBD = false;
  29881. /** @hidden */
  29882. this._references = 1;
  29883. this._engine = engine;
  29884. this._dataSource = dataSource;
  29885. this._webGLTexture = engine._createTexture();
  29886. }
  29887. /**
  29888. * Gets the Engine the texture belongs to.
  29889. * @returns The babylon engine
  29890. */
  29891. InternalTexture.prototype.getEngine = function () {
  29892. return this._engine;
  29893. };
  29894. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29895. /**
  29896. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29897. */
  29898. get: function () {
  29899. return this._dataSource;
  29900. },
  29901. enumerable: true,
  29902. configurable: true
  29903. });
  29904. /**
  29905. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29906. */
  29907. InternalTexture.prototype.incrementReferences = function () {
  29908. this._references++;
  29909. };
  29910. /**
  29911. * Change the size of the texture (not the size of the content)
  29912. * @param width defines the new width
  29913. * @param height defines the new height
  29914. * @param depth defines the new depth (1 by default)
  29915. */
  29916. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29917. if (depth === void 0) { depth = 1; }
  29918. this.width = width;
  29919. this.height = height;
  29920. this.depth = depth;
  29921. this.baseWidth = width;
  29922. this.baseHeight = height;
  29923. this.baseDepth = depth;
  29924. this._size = width * height * depth;
  29925. };
  29926. /** @hidden */
  29927. InternalTexture.prototype._rebuild = function () {
  29928. var _this = this;
  29929. var proxy;
  29930. this.isReady = false;
  29931. this._cachedCoordinatesMode = null;
  29932. this._cachedWrapU = null;
  29933. this._cachedWrapV = null;
  29934. this._cachedAnisotropicFilteringLevel = null;
  29935. switch (this._dataSource) {
  29936. case InternalTexture.DATASOURCE_TEMP:
  29937. return;
  29938. case InternalTexture.DATASOURCE_URL:
  29939. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29940. _this.isReady = true;
  29941. }, null, this._buffer, undefined, this.format);
  29942. proxy._swapAndDie(this);
  29943. return;
  29944. case InternalTexture.DATASOURCE_RAW:
  29945. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29946. proxy._swapAndDie(this);
  29947. this.isReady = true;
  29948. return;
  29949. case InternalTexture.DATASOURCE_RAW3D:
  29950. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29951. proxy._swapAndDie(this);
  29952. this.isReady = true;
  29953. return;
  29954. case InternalTexture.DATASOURCE_DYNAMIC:
  29955. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29956. proxy._swapAndDie(this);
  29957. // The engine will make sure to update content so no need to flag it as isReady = true
  29958. return;
  29959. case InternalTexture.DATASOURCE_RENDERTARGET:
  29960. var options = new BABYLON.RenderTargetCreationOptions();
  29961. options.generateDepthBuffer = this._generateDepthBuffer;
  29962. options.generateMipMaps = this.generateMipMaps;
  29963. options.generateStencilBuffer = this._generateStencilBuffer;
  29964. options.samplingMode = this.samplingMode;
  29965. options.type = this.type;
  29966. if (this.isCube) {
  29967. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29968. }
  29969. else {
  29970. var size = {
  29971. width: this.width,
  29972. height: this.height
  29973. };
  29974. proxy = this._engine.createRenderTargetTexture(size, options);
  29975. }
  29976. proxy._swapAndDie(this);
  29977. this.isReady = true;
  29978. return;
  29979. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29980. var depthTextureOptions = {
  29981. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29982. comparisonFunction: this._comparisonFunction,
  29983. generateStencil: this._generateStencilBuffer,
  29984. isCube: this.isCube
  29985. };
  29986. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29987. proxy._swapAndDie(this);
  29988. this.isReady = true;
  29989. return;
  29990. case InternalTexture.DATASOURCE_CUBE:
  29991. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29992. _this.isReady = true;
  29993. }, null, this.format, this._extension);
  29994. proxy._swapAndDie(this);
  29995. return;
  29996. case InternalTexture.DATASOURCE_CUBERAW:
  29997. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29998. proxy._swapAndDie(this);
  29999. this.isReady = true;
  30000. return;
  30001. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30002. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30003. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30004. _this.isReady = true;
  30005. });
  30006. proxy._swapAndDie(this);
  30007. return;
  30008. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30009. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30010. if (proxy) {
  30011. proxy._swapAndDie(_this);
  30012. }
  30013. _this.isReady = true;
  30014. }, null, this.format, this._extension);
  30015. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30016. return;
  30017. }
  30018. };
  30019. /** @hidden */
  30020. InternalTexture.prototype._swapAndDie = function (target) {
  30021. target._webGLTexture = this._webGLTexture;
  30022. if (this._framebuffer) {
  30023. target._framebuffer = this._framebuffer;
  30024. }
  30025. if (this._depthStencilBuffer) {
  30026. target._depthStencilBuffer = this._depthStencilBuffer;
  30027. }
  30028. if (this._lodTextureHigh) {
  30029. if (target._lodTextureHigh) {
  30030. target._lodTextureHigh.dispose();
  30031. }
  30032. target._lodTextureHigh = this._lodTextureHigh;
  30033. }
  30034. if (this._lodTextureMid) {
  30035. if (target._lodTextureMid) {
  30036. target._lodTextureMid.dispose();
  30037. }
  30038. target._lodTextureMid = this._lodTextureMid;
  30039. }
  30040. if (this._lodTextureLow) {
  30041. if (target._lodTextureLow) {
  30042. target._lodTextureLow.dispose();
  30043. }
  30044. target._lodTextureLow = this._lodTextureLow;
  30045. }
  30046. var cache = this._engine.getLoadedTexturesCache();
  30047. var index = cache.indexOf(this);
  30048. if (index !== -1) {
  30049. cache.splice(index, 1);
  30050. }
  30051. };
  30052. /**
  30053. * Dispose the current allocated resources
  30054. */
  30055. InternalTexture.prototype.dispose = function () {
  30056. if (!this._webGLTexture) {
  30057. return;
  30058. }
  30059. this._references--;
  30060. if (this._references === 0) {
  30061. this._engine._releaseTexture(this);
  30062. this._webGLTexture = null;
  30063. this.previous = null;
  30064. this.next = null;
  30065. }
  30066. };
  30067. /**
  30068. * The source of the texture data is unknown
  30069. */
  30070. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30071. /**
  30072. * Texture data comes from an URL
  30073. */
  30074. InternalTexture.DATASOURCE_URL = 1;
  30075. /**
  30076. * Texture data is only used for temporary storage
  30077. */
  30078. InternalTexture.DATASOURCE_TEMP = 2;
  30079. /**
  30080. * Texture data comes from raw data (ArrayBuffer)
  30081. */
  30082. InternalTexture.DATASOURCE_RAW = 3;
  30083. /**
  30084. * Texture content is dynamic (video or dynamic texture)
  30085. */
  30086. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30087. /**
  30088. * Texture content is generated by rendering to it
  30089. */
  30090. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30091. /**
  30092. * Texture content is part of a multi render target process
  30093. */
  30094. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30095. /**
  30096. * Texture data comes from a cube data file
  30097. */
  30098. InternalTexture.DATASOURCE_CUBE = 7;
  30099. /**
  30100. * Texture data comes from a raw cube data
  30101. */
  30102. InternalTexture.DATASOURCE_CUBERAW = 8;
  30103. /**
  30104. * Texture data come from a prefiltered cube data file
  30105. */
  30106. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30107. /**
  30108. * Texture content is raw 3D data
  30109. */
  30110. InternalTexture.DATASOURCE_RAW3D = 10;
  30111. /**
  30112. * Texture content is a depth texture
  30113. */
  30114. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30115. /**
  30116. * Texture data comes from a raw cube data encoded with RGBD
  30117. */
  30118. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30119. return InternalTexture;
  30120. }());
  30121. BABYLON.InternalTexture = InternalTexture;
  30122. })(BABYLON || (BABYLON = {}));
  30123. //# sourceMappingURL=babylon.internalTexture.js.map
  30124. var BABYLON;
  30125. (function (BABYLON) {
  30126. var BaseTexture = /** @class */ (function () {
  30127. function BaseTexture(scene) {
  30128. this._hasAlpha = false;
  30129. this.getAlphaFromRGB = false;
  30130. this.level = 1;
  30131. this.coordinatesIndex = 0;
  30132. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30133. /**
  30134. * | Value | Type | Description |
  30135. * | ----- | ------------------ | ----------- |
  30136. * | 0 | CLAMP_ADDRESSMODE | |
  30137. * | 1 | WRAP_ADDRESSMODE | |
  30138. * | 2 | MIRROR_ADDRESSMODE | |
  30139. */
  30140. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30141. /**
  30142. * | Value | Type | Description |
  30143. * | ----- | ------------------ | ----------- |
  30144. * | 0 | CLAMP_ADDRESSMODE | |
  30145. * | 1 | WRAP_ADDRESSMODE | |
  30146. * | 2 | MIRROR_ADDRESSMODE | |
  30147. */
  30148. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30149. /**
  30150. * | Value | Type | Description |
  30151. * | ----- | ------------------ | ----------- |
  30152. * | 0 | CLAMP_ADDRESSMODE | |
  30153. * | 1 | WRAP_ADDRESSMODE | |
  30154. * | 2 | MIRROR_ADDRESSMODE | |
  30155. */
  30156. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30157. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30158. this.isCube = false;
  30159. this.is3D = false;
  30160. this.gammaSpace = true;
  30161. this.invertZ = false;
  30162. this.lodLevelInAlpha = false;
  30163. this.isRenderTarget = false;
  30164. this.animations = new Array();
  30165. /**
  30166. * An event triggered when the texture is disposed.
  30167. */
  30168. this.onDisposeObservable = new BABYLON.Observable();
  30169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30170. this._cachedSize = BABYLON.Size.Zero();
  30171. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30172. if (this._scene) {
  30173. this._scene.textures.push(this);
  30174. }
  30175. this._uid = null;
  30176. }
  30177. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30178. get: function () {
  30179. return this._hasAlpha;
  30180. },
  30181. set: function (value) {
  30182. if (this._hasAlpha === value) {
  30183. return;
  30184. }
  30185. this._hasAlpha = value;
  30186. if (this._scene) {
  30187. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30188. }
  30189. },
  30190. enumerable: true,
  30191. configurable: true
  30192. });
  30193. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30194. get: function () {
  30195. return this._coordinatesMode;
  30196. },
  30197. /**
  30198. * How a texture is mapped.
  30199. *
  30200. * | Value | Type | Description |
  30201. * | ----- | ----------------------------------- | ----------- |
  30202. * | 0 | EXPLICIT_MODE | |
  30203. * | 1 | SPHERICAL_MODE | |
  30204. * | 2 | PLANAR_MODE | |
  30205. * | 3 | CUBIC_MODE | |
  30206. * | 4 | PROJECTION_MODE | |
  30207. * | 5 | SKYBOX_MODE | |
  30208. * | 6 | INVCUBIC_MODE | |
  30209. * | 7 | EQUIRECTANGULAR_MODE | |
  30210. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30211. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30212. */
  30213. set: function (value) {
  30214. if (this._coordinatesMode === value) {
  30215. return;
  30216. }
  30217. this._coordinatesMode = value;
  30218. if (this._scene) {
  30219. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30220. }
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30226. /**
  30227. * Gets whether or not the texture contains RGBD data.
  30228. */
  30229. get: function () {
  30230. return this._texture != null && this._texture._isRGBD;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30236. get: function () {
  30237. if (this._texture)
  30238. return this._texture._lodGenerationOffset;
  30239. return 0.0;
  30240. },
  30241. set: function (value) {
  30242. if (this._texture)
  30243. this._texture._lodGenerationOffset = value;
  30244. },
  30245. enumerable: true,
  30246. configurable: true
  30247. });
  30248. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30249. get: function () {
  30250. if (this._texture)
  30251. return this._texture._lodGenerationScale;
  30252. return 0.0;
  30253. },
  30254. set: function (value) {
  30255. if (this._texture)
  30256. this._texture._lodGenerationScale = value;
  30257. },
  30258. enumerable: true,
  30259. configurable: true
  30260. });
  30261. Object.defineProperty(BaseTexture.prototype, "uid", {
  30262. get: function () {
  30263. if (!this._uid) {
  30264. this._uid = BABYLON.Tools.RandomId();
  30265. }
  30266. return this._uid;
  30267. },
  30268. enumerable: true,
  30269. configurable: true
  30270. });
  30271. BaseTexture.prototype.toString = function () {
  30272. return this.name;
  30273. };
  30274. BaseTexture.prototype.getClassName = function () {
  30275. return "BaseTexture";
  30276. };
  30277. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30278. set: function (callback) {
  30279. if (this._onDisposeObserver) {
  30280. this.onDisposeObservable.remove(this._onDisposeObserver);
  30281. }
  30282. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30283. },
  30284. enumerable: true,
  30285. configurable: true
  30286. });
  30287. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30288. get: function () {
  30289. return true;
  30290. },
  30291. enumerable: true,
  30292. configurable: true
  30293. });
  30294. BaseTexture.prototype.getScene = function () {
  30295. return this._scene;
  30296. };
  30297. BaseTexture.prototype.getTextureMatrix = function () {
  30298. return BABYLON.Matrix.IdentityReadOnly;
  30299. };
  30300. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30301. return BABYLON.Matrix.IdentityReadOnly;
  30302. };
  30303. BaseTexture.prototype.getInternalTexture = function () {
  30304. return this._texture;
  30305. };
  30306. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30307. return !this.isBlocking || this.isReady();
  30308. };
  30309. BaseTexture.prototype.isReady = function () {
  30310. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30311. this.delayLoad();
  30312. return false;
  30313. }
  30314. if (this._texture) {
  30315. return this._texture.isReady;
  30316. }
  30317. return false;
  30318. };
  30319. BaseTexture.prototype.getSize = function () {
  30320. if (this._texture) {
  30321. if (this._texture.width) {
  30322. this._cachedSize.width = this._texture.width;
  30323. this._cachedSize.height = this._texture.height;
  30324. return this._cachedSize;
  30325. }
  30326. if (this._texture._size) {
  30327. this._cachedSize.width = this._texture._size;
  30328. this._cachedSize.height = this._texture._size;
  30329. return this._cachedSize;
  30330. }
  30331. }
  30332. return this._cachedSize;
  30333. };
  30334. BaseTexture.prototype.getBaseSize = function () {
  30335. if (!this.isReady() || !this._texture)
  30336. return BABYLON.Size.Zero();
  30337. if (this._texture._size) {
  30338. return new BABYLON.Size(this._texture._size, this._texture._size);
  30339. }
  30340. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30341. };
  30342. BaseTexture.prototype.scale = function (ratio) {
  30343. };
  30344. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30345. get: function () {
  30346. return false;
  30347. },
  30348. enumerable: true,
  30349. configurable: true
  30350. });
  30351. /** @hidden */
  30352. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30353. if (!this._scene) {
  30354. return null;
  30355. }
  30356. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30357. for (var index = 0; index < texturesCache.length; index++) {
  30358. var texturesCacheEntry = texturesCache[index];
  30359. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30360. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30361. texturesCacheEntry.incrementReferences();
  30362. return texturesCacheEntry;
  30363. }
  30364. }
  30365. }
  30366. return null;
  30367. };
  30368. /** @hidden */
  30369. BaseTexture.prototype._rebuild = function () {
  30370. };
  30371. BaseTexture.prototype.delayLoad = function () {
  30372. };
  30373. BaseTexture.prototype.clone = function () {
  30374. return null;
  30375. };
  30376. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30377. get: function () {
  30378. if (!this._texture) {
  30379. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30380. }
  30381. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30382. },
  30383. enumerable: true,
  30384. configurable: true
  30385. });
  30386. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30387. get: function () {
  30388. if (!this._texture) {
  30389. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30390. }
  30391. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30392. },
  30393. enumerable: true,
  30394. configurable: true
  30395. });
  30396. /**
  30397. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30398. * This will returns an RGBA array buffer containing either in values (0-255) or
  30399. * float values (0-1) depending of the underlying buffer type.
  30400. * @param faceIndex The face of the texture to read (in case of cube texture)
  30401. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30402. * @returns The Array buffer containing the pixels data.
  30403. */
  30404. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30405. if (faceIndex === void 0) { faceIndex = 0; }
  30406. if (level === void 0) { level = 0; }
  30407. if (!this._texture) {
  30408. return null;
  30409. }
  30410. var size = this.getSize();
  30411. var width = size.width;
  30412. var height = size.height;
  30413. var scene = this.getScene();
  30414. if (!scene) {
  30415. return null;
  30416. }
  30417. var engine = scene.getEngine();
  30418. if (level != 0) {
  30419. width = width / Math.pow(2, level);
  30420. height = height / Math.pow(2, level);
  30421. width = Math.round(width);
  30422. height = Math.round(height);
  30423. }
  30424. if (this._texture.isCube) {
  30425. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30426. }
  30427. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30428. };
  30429. BaseTexture.prototype.releaseInternalTexture = function () {
  30430. if (this._texture) {
  30431. this._texture.dispose();
  30432. this._texture = null;
  30433. }
  30434. };
  30435. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30436. get: function () {
  30437. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30438. return null;
  30439. }
  30440. if (!this._texture._sphericalPolynomial) {
  30441. this._texture._sphericalPolynomial =
  30442. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30443. }
  30444. return this._texture._sphericalPolynomial;
  30445. },
  30446. set: function (value) {
  30447. if (this._texture) {
  30448. this._texture._sphericalPolynomial = value;
  30449. }
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30455. get: function () {
  30456. if (this._texture) {
  30457. return this._texture._lodTextureHigh;
  30458. }
  30459. return null;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30465. get: function () {
  30466. if (this._texture) {
  30467. return this._texture._lodTextureMid;
  30468. }
  30469. return null;
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30475. get: function () {
  30476. if (this._texture) {
  30477. return this._texture._lodTextureLow;
  30478. }
  30479. return null;
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. BaseTexture.prototype.dispose = function () {
  30485. if (!this._scene) {
  30486. return;
  30487. }
  30488. // Animations
  30489. this._scene.stopAnimation(this);
  30490. // Remove from scene
  30491. this._scene._removePendingData(this);
  30492. var index = this._scene.textures.indexOf(this);
  30493. if (index >= 0) {
  30494. this._scene.textures.splice(index, 1);
  30495. }
  30496. if (this._texture === undefined) {
  30497. return;
  30498. }
  30499. // Release
  30500. this.releaseInternalTexture();
  30501. // Callback
  30502. this.onDisposeObservable.notifyObservers(this);
  30503. this.onDisposeObservable.clear();
  30504. };
  30505. BaseTexture.prototype.serialize = function () {
  30506. if (!this.name) {
  30507. return null;
  30508. }
  30509. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30510. // Animations
  30511. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30512. return serializationObject;
  30513. };
  30514. BaseTexture.WhenAllReady = function (textures, callback) {
  30515. var numRemaining = textures.length;
  30516. if (numRemaining === 0) {
  30517. callback();
  30518. return;
  30519. }
  30520. var _loop_1 = function () {
  30521. texture = textures[i];
  30522. if (texture.isReady()) {
  30523. if (--numRemaining === 0) {
  30524. callback();
  30525. }
  30526. }
  30527. else {
  30528. onLoadObservable = texture.onLoadObservable;
  30529. var onLoadCallback_1 = function () {
  30530. onLoadObservable.removeCallback(onLoadCallback_1);
  30531. if (--numRemaining === 0) {
  30532. callback();
  30533. }
  30534. };
  30535. onLoadObservable.add(onLoadCallback_1);
  30536. }
  30537. };
  30538. var texture, onLoadObservable;
  30539. for (var i = 0; i < textures.length; i++) {
  30540. _loop_1();
  30541. }
  30542. };
  30543. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30544. __decorate([
  30545. BABYLON.serialize()
  30546. ], BaseTexture.prototype, "name", void 0);
  30547. __decorate([
  30548. BABYLON.serialize("hasAlpha")
  30549. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30550. __decorate([
  30551. BABYLON.serialize()
  30552. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30553. __decorate([
  30554. BABYLON.serialize()
  30555. ], BaseTexture.prototype, "level", void 0);
  30556. __decorate([
  30557. BABYLON.serialize()
  30558. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30559. __decorate([
  30560. BABYLON.serialize("coordinatesMode")
  30561. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30562. __decorate([
  30563. BABYLON.serialize()
  30564. ], BaseTexture.prototype, "wrapU", void 0);
  30565. __decorate([
  30566. BABYLON.serialize()
  30567. ], BaseTexture.prototype, "wrapV", void 0);
  30568. __decorate([
  30569. BABYLON.serialize()
  30570. ], BaseTexture.prototype, "wrapR", void 0);
  30571. __decorate([
  30572. BABYLON.serialize()
  30573. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30574. __decorate([
  30575. BABYLON.serialize()
  30576. ], BaseTexture.prototype, "isCube", void 0);
  30577. __decorate([
  30578. BABYLON.serialize()
  30579. ], BaseTexture.prototype, "is3D", void 0);
  30580. __decorate([
  30581. BABYLON.serialize()
  30582. ], BaseTexture.prototype, "gammaSpace", void 0);
  30583. __decorate([
  30584. BABYLON.serialize()
  30585. ], BaseTexture.prototype, "invertZ", void 0);
  30586. __decorate([
  30587. BABYLON.serialize()
  30588. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30589. __decorate([
  30590. BABYLON.serialize()
  30591. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30592. __decorate([
  30593. BABYLON.serialize()
  30594. ], BaseTexture.prototype, "lodGenerationScale", null);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30598. return BaseTexture;
  30599. }());
  30600. BABYLON.BaseTexture = BaseTexture;
  30601. })(BABYLON || (BABYLON = {}));
  30602. //# sourceMappingURL=babylon.baseTexture.js.map
  30603. var BABYLON;
  30604. (function (BABYLON) {
  30605. var Texture = /** @class */ (function (_super) {
  30606. __extends(Texture, _super);
  30607. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30608. if (noMipmap === void 0) { noMipmap = false; }
  30609. if (invertY === void 0) { invertY = true; }
  30610. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30611. if (onLoad === void 0) { onLoad = null; }
  30612. if (onError === void 0) { onError = null; }
  30613. if (buffer === void 0) { buffer = null; }
  30614. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30615. var _this = _super.call(this, scene) || this;
  30616. _this.uOffset = 0;
  30617. _this.vOffset = 0;
  30618. _this.uScale = 1.0;
  30619. _this.vScale = 1.0;
  30620. _this.uAng = 0;
  30621. _this.vAng = 0;
  30622. _this.wAng = 0;
  30623. /**
  30624. * Defines the center of rotation (U)
  30625. */
  30626. _this.uRotationCenter = 0.5;
  30627. /**
  30628. * Defines the center of rotation (V)
  30629. */
  30630. _this.vRotationCenter = 0.5;
  30631. /**
  30632. * Defines the center of rotation (W)
  30633. */
  30634. _this.wRotationCenter = 0.5;
  30635. _this._isBlocking = true;
  30636. _this.name = url || "";
  30637. _this.url = url;
  30638. _this._noMipmap = noMipmap;
  30639. _this._invertY = invertY;
  30640. _this._samplingMode = samplingMode;
  30641. _this._buffer = buffer;
  30642. _this._deleteBuffer = deleteBuffer;
  30643. if (format) {
  30644. _this._format = format;
  30645. }
  30646. scene = _this.getScene();
  30647. if (!scene) {
  30648. return _this;
  30649. }
  30650. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30651. var load = function () {
  30652. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30653. _this.onLoadObservable.notifyObservers(_this);
  30654. }
  30655. if (onLoad) {
  30656. onLoad();
  30657. }
  30658. if (!_this.isBlocking && scene) {
  30659. scene.resetCachedMaterial();
  30660. }
  30661. };
  30662. if (!_this.url) {
  30663. _this._delayedOnLoad = load;
  30664. _this._delayedOnError = onError;
  30665. return _this;
  30666. }
  30667. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30668. if (!_this._texture) {
  30669. if (!scene.useDelayedTextureLoading) {
  30670. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30671. if (deleteBuffer) {
  30672. delete _this._buffer;
  30673. }
  30674. }
  30675. else {
  30676. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30677. _this._delayedOnLoad = load;
  30678. _this._delayedOnError = onError;
  30679. }
  30680. }
  30681. else {
  30682. if (_this._texture.isReady) {
  30683. BABYLON.Tools.SetImmediate(function () { return load(); });
  30684. }
  30685. else {
  30686. _this._texture.onLoadedObservable.add(load);
  30687. }
  30688. }
  30689. return _this;
  30690. }
  30691. Object.defineProperty(Texture.prototype, "noMipmap", {
  30692. get: function () {
  30693. return this._noMipmap;
  30694. },
  30695. enumerable: true,
  30696. configurable: true
  30697. });
  30698. Object.defineProperty(Texture.prototype, "isBlocking", {
  30699. get: function () {
  30700. return this._isBlocking;
  30701. },
  30702. set: function (value) {
  30703. this._isBlocking = value;
  30704. },
  30705. enumerable: true,
  30706. configurable: true
  30707. });
  30708. Object.defineProperty(Texture.prototype, "samplingMode", {
  30709. get: function () {
  30710. return this._samplingMode;
  30711. },
  30712. enumerable: true,
  30713. configurable: true
  30714. });
  30715. /**
  30716. * Update the url (and optional buffer) of this texture if url was null during construction.
  30717. * @param url the url of the texture
  30718. * @param buffer the buffer of the texture (defaults to null)
  30719. */
  30720. Texture.prototype.updateURL = function (url, buffer) {
  30721. if (buffer === void 0) { buffer = null; }
  30722. if (this.url) {
  30723. throw new Error("URL is already set");
  30724. }
  30725. this.url = url;
  30726. this._buffer = buffer;
  30727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30728. this.delayLoad();
  30729. };
  30730. Texture.prototype.delayLoad = function () {
  30731. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30732. return;
  30733. }
  30734. var scene = this.getScene();
  30735. if (!scene) {
  30736. return;
  30737. }
  30738. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30739. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30740. if (!this._texture) {
  30741. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30742. if (this._deleteBuffer) {
  30743. delete this._buffer;
  30744. }
  30745. }
  30746. else {
  30747. if (this._delayedOnLoad) {
  30748. if (this._texture.isReady) {
  30749. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30750. }
  30751. else {
  30752. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30753. }
  30754. }
  30755. }
  30756. this._delayedOnLoad = null;
  30757. this._delayedOnError = null;
  30758. };
  30759. /**
  30760. * Default is Trilinear mode.
  30761. *
  30762. * | Value | Type | Description |
  30763. * | ----- | ------------------ | ----------- |
  30764. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30765. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30766. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30767. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30768. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30769. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30770. * | 7 | NEAREST_LINEAR | |
  30771. * | 8 | NEAREST_NEAREST | |
  30772. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30773. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30774. * | 11 | LINEAR_LINEAR | |
  30775. * | 12 | LINEAR_NEAREST | |
  30776. *
  30777. * > _mag_: magnification filter (close to the viewer)
  30778. * > _min_: minification filter (far from the viewer)
  30779. * > _mip_: filter used between mip map levels
  30780. *
  30781. */
  30782. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30783. if (!this._texture) {
  30784. return;
  30785. }
  30786. var scene = this.getScene();
  30787. if (!scene) {
  30788. return;
  30789. }
  30790. this._samplingMode = samplingMode;
  30791. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30792. };
  30793. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30794. x *= this.uScale;
  30795. y *= this.vScale;
  30796. x -= this.uRotationCenter * this.uScale;
  30797. y -= this.vRotationCenter * this.vScale;
  30798. z -= this.wRotationCenter;
  30799. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30800. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30801. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30802. t.z += this.wRotationCenter;
  30803. };
  30804. Texture.prototype.getTextureMatrix = function () {
  30805. var _this = this;
  30806. if (this.uOffset === this._cachedUOffset &&
  30807. this.vOffset === this._cachedVOffset &&
  30808. this.uScale === this._cachedUScale &&
  30809. this.vScale === this._cachedVScale &&
  30810. this.uAng === this._cachedUAng &&
  30811. this.vAng === this._cachedVAng &&
  30812. this.wAng === this._cachedWAng) {
  30813. return this._cachedTextureMatrix;
  30814. }
  30815. this._cachedUOffset = this.uOffset;
  30816. this._cachedVOffset = this.vOffset;
  30817. this._cachedUScale = this.uScale;
  30818. this._cachedVScale = this.vScale;
  30819. this._cachedUAng = this.uAng;
  30820. this._cachedVAng = this.vAng;
  30821. this._cachedWAng = this.wAng;
  30822. if (!this._cachedTextureMatrix) {
  30823. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30824. this._rowGenerationMatrix = new BABYLON.Matrix();
  30825. this._t0 = BABYLON.Vector3.Zero();
  30826. this._t1 = BABYLON.Vector3.Zero();
  30827. this._t2 = BABYLON.Vector3.Zero();
  30828. }
  30829. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30830. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30831. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30832. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30833. this._t1.subtractInPlace(this._t0);
  30834. this._t2.subtractInPlace(this._t0);
  30835. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30836. this._cachedTextureMatrix.m[0] = this._t1.x;
  30837. this._cachedTextureMatrix.m[1] = this._t1.y;
  30838. this._cachedTextureMatrix.m[2] = this._t1.z;
  30839. this._cachedTextureMatrix.m[4] = this._t2.x;
  30840. this._cachedTextureMatrix.m[5] = this._t2.y;
  30841. this._cachedTextureMatrix.m[6] = this._t2.z;
  30842. this._cachedTextureMatrix.m[8] = this._t0.x;
  30843. this._cachedTextureMatrix.m[9] = this._t0.y;
  30844. this._cachedTextureMatrix.m[10] = this._t0.z;
  30845. var scene = this.getScene();
  30846. if (!scene) {
  30847. return this._cachedTextureMatrix;
  30848. }
  30849. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30850. return mat.hasTexture(_this);
  30851. });
  30852. return this._cachedTextureMatrix;
  30853. };
  30854. Texture.prototype.getReflectionTextureMatrix = function () {
  30855. var _this = this;
  30856. var scene = this.getScene();
  30857. if (!scene) {
  30858. return this._cachedTextureMatrix;
  30859. }
  30860. if (this.uOffset === this._cachedUOffset &&
  30861. this.vOffset === this._cachedVOffset &&
  30862. this.uScale === this._cachedUScale &&
  30863. this.vScale === this._cachedVScale &&
  30864. this.coordinatesMode === this._cachedCoordinatesMode) {
  30865. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30866. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30867. return this._cachedTextureMatrix;
  30868. }
  30869. }
  30870. else {
  30871. return this._cachedTextureMatrix;
  30872. }
  30873. }
  30874. if (!this._cachedTextureMatrix) {
  30875. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30876. }
  30877. if (!this._projectionModeMatrix) {
  30878. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30879. }
  30880. this._cachedUOffset = this.uOffset;
  30881. this._cachedVOffset = this.vOffset;
  30882. this._cachedUScale = this.uScale;
  30883. this._cachedVScale = this.vScale;
  30884. this._cachedCoordinatesMode = this.coordinatesMode;
  30885. switch (this.coordinatesMode) {
  30886. case Texture.PLANAR_MODE:
  30887. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30888. this._cachedTextureMatrix[0] = this.uScale;
  30889. this._cachedTextureMatrix[5] = this.vScale;
  30890. this._cachedTextureMatrix[12] = this.uOffset;
  30891. this._cachedTextureMatrix[13] = this.vOffset;
  30892. break;
  30893. case Texture.PROJECTION_MODE:
  30894. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30895. this._projectionModeMatrix.m[0] = 0.5;
  30896. this._projectionModeMatrix.m[5] = -0.5;
  30897. this._projectionModeMatrix.m[10] = 0.0;
  30898. this._projectionModeMatrix.m[12] = 0.5;
  30899. this._projectionModeMatrix.m[13] = 0.5;
  30900. this._projectionModeMatrix.m[14] = 1.0;
  30901. this._projectionModeMatrix.m[15] = 1.0;
  30902. var projectionMatrix = scene.getProjectionMatrix();
  30903. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30904. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30905. break;
  30906. default:
  30907. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30908. break;
  30909. }
  30910. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30911. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30912. });
  30913. return this._cachedTextureMatrix;
  30914. };
  30915. Texture.prototype.clone = function () {
  30916. var _this = this;
  30917. return BABYLON.SerializationHelper.Clone(function () {
  30918. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30919. }, this);
  30920. };
  30921. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30922. get: function () {
  30923. if (!this._onLoadObservable) {
  30924. this._onLoadObservable = new BABYLON.Observable();
  30925. }
  30926. return this._onLoadObservable;
  30927. },
  30928. enumerable: true,
  30929. configurable: true
  30930. });
  30931. Texture.prototype.serialize = function () {
  30932. var serializationObject = _super.prototype.serialize.call(this);
  30933. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30934. serializationObject.base64String = this._buffer;
  30935. serializationObject.name = serializationObject.name.replace("data:", "");
  30936. }
  30937. serializationObject.invertY = this._invertY;
  30938. serializationObject.samplingMode = this.samplingMode;
  30939. return serializationObject;
  30940. };
  30941. Texture.prototype.getClassName = function () {
  30942. return "Texture";
  30943. };
  30944. Texture.prototype.dispose = function () {
  30945. _super.prototype.dispose.call(this);
  30946. if (this._onLoadObservable) {
  30947. this._onLoadObservable.clear();
  30948. this._onLoadObservable = null;
  30949. }
  30950. this._delayedOnLoad = null;
  30951. this._delayedOnError = null;
  30952. };
  30953. // Statics
  30954. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30955. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30956. if (onLoad === void 0) { onLoad = null; }
  30957. if (onError === void 0) { onError = null; }
  30958. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30959. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30960. };
  30961. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30962. if (parsedTexture.customType) {
  30963. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30964. // Update Sampling Mode
  30965. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30966. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30967. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30968. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30969. }
  30970. }
  30971. return parsedCustomTexture;
  30972. }
  30973. if (parsedTexture.isCube) {
  30974. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30975. }
  30976. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30977. return null;
  30978. }
  30979. var texture = BABYLON.SerializationHelper.Parse(function () {
  30980. var generateMipMaps = true;
  30981. if (parsedTexture.noMipmap) {
  30982. generateMipMaps = false;
  30983. }
  30984. if (parsedTexture.mirrorPlane) {
  30985. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30986. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30987. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30988. return mirrorTexture;
  30989. }
  30990. else if (parsedTexture.isRenderTarget) {
  30991. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30992. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30993. return renderTargetTexture;
  30994. }
  30995. else {
  30996. var texture;
  30997. if (parsedTexture.base64String) {
  30998. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30999. }
  31000. else {
  31001. var url = rootUrl + parsedTexture.name;
  31002. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31003. url = parsedTexture.url;
  31004. }
  31005. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31006. }
  31007. return texture;
  31008. }
  31009. }, parsedTexture, scene);
  31010. // Update Sampling Mode
  31011. if (parsedTexture.samplingMode) {
  31012. var sampling = parsedTexture.samplingMode;
  31013. if (texture._samplingMode !== sampling) {
  31014. texture.updateSamplingMode(sampling);
  31015. }
  31016. }
  31017. // Animations
  31018. if (parsedTexture.animations) {
  31019. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31020. var parsedAnimation = parsedTexture.animations[animationIndex];
  31021. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31022. }
  31023. }
  31024. return texture;
  31025. };
  31026. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31027. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31028. if (noMipmap === void 0) { noMipmap = false; }
  31029. if (invertY === void 0) { invertY = true; }
  31030. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31031. if (onLoad === void 0) { onLoad = null; }
  31032. if (onError === void 0) { onError = null; }
  31033. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31034. if (name.substr(0, 5) !== "data:") {
  31035. name = "data:" + name;
  31036. }
  31037. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31038. };
  31039. // Constants
  31040. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31041. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31042. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31043. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31044. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31045. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31046. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31047. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31048. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31049. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31050. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31051. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31052. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31053. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31054. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31055. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31056. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31057. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31058. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31059. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31060. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31061. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31062. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31063. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31064. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31065. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31066. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31067. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31068. /**
  31069. * 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
  31070. */
  31071. Texture.UseSerializedUrlIfAny = false;
  31072. __decorate([
  31073. BABYLON.serialize()
  31074. ], Texture.prototype, "url", void 0);
  31075. __decorate([
  31076. BABYLON.serialize()
  31077. ], Texture.prototype, "uOffset", void 0);
  31078. __decorate([
  31079. BABYLON.serialize()
  31080. ], Texture.prototype, "vOffset", void 0);
  31081. __decorate([
  31082. BABYLON.serialize()
  31083. ], Texture.prototype, "uScale", void 0);
  31084. __decorate([
  31085. BABYLON.serialize()
  31086. ], Texture.prototype, "vScale", void 0);
  31087. __decorate([
  31088. BABYLON.serialize()
  31089. ], Texture.prototype, "uAng", void 0);
  31090. __decorate([
  31091. BABYLON.serialize()
  31092. ], Texture.prototype, "vAng", void 0);
  31093. __decorate([
  31094. BABYLON.serialize()
  31095. ], Texture.prototype, "wAng", void 0);
  31096. __decorate([
  31097. BABYLON.serialize()
  31098. ], Texture.prototype, "uRotationCenter", void 0);
  31099. __decorate([
  31100. BABYLON.serialize()
  31101. ], Texture.prototype, "vRotationCenter", void 0);
  31102. __decorate([
  31103. BABYLON.serialize()
  31104. ], Texture.prototype, "wRotationCenter", void 0);
  31105. __decorate([
  31106. BABYLON.serialize()
  31107. ], Texture.prototype, "isBlocking", null);
  31108. return Texture;
  31109. }(BABYLON.BaseTexture));
  31110. BABYLON.Texture = Texture;
  31111. })(BABYLON || (BABYLON = {}));
  31112. //# sourceMappingURL=babylon.texture.js.map
  31113. var BABYLON;
  31114. (function (BABYLON) {
  31115. /**
  31116. * @hidden
  31117. **/
  31118. var _InstancesBatch = /** @class */ (function () {
  31119. function _InstancesBatch() {
  31120. this.mustReturn = false;
  31121. this.visibleInstances = new Array();
  31122. this.renderSelf = new Array();
  31123. }
  31124. return _InstancesBatch;
  31125. }());
  31126. BABYLON._InstancesBatch = _InstancesBatch;
  31127. var Mesh = /** @class */ (function (_super) {
  31128. __extends(Mesh, _super);
  31129. /**
  31130. * @constructor
  31131. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31132. * @param {Scene} scene The scene to add this mesh to.
  31133. * @param {Node} parent The parent of this mesh, if it has one
  31134. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31135. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31136. * When false, achieved by calling a clone(), also passing False.
  31137. * This will make creation of children, recursive.
  31138. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31139. */
  31140. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31141. if (scene === void 0) { scene = null; }
  31142. if (parent === void 0) { parent = null; }
  31143. if (source === void 0) { source = null; }
  31144. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31145. var _this = _super.call(this, name, scene) || this;
  31146. // Members
  31147. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31148. _this.instances = new Array();
  31149. _this._LODLevels = new Array();
  31150. /** @hidden */
  31151. _this._visibleInstances = {};
  31152. _this._renderIdForInstances = new Array();
  31153. _this._batchCache = new _InstancesBatch();
  31154. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31155. // Use by builder only to know what orientation were the mesh build in.
  31156. /** @hidden */
  31157. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31158. _this.overrideMaterialSideOrientation = null;
  31159. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31160. // Will be used to save a source mesh reference, If any
  31161. _this._source = null;
  31162. scene = _this.getScene();
  31163. if (source) {
  31164. // Geometry
  31165. if (source._geometry) {
  31166. source._geometry.applyToMesh(_this);
  31167. }
  31168. // Deep copy
  31169. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31170. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31171. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31172. ], ["_poseMatrix"]);
  31173. // Source mesh
  31174. _this._source = source;
  31175. // Construction Params
  31176. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31177. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31178. var myAnyThis = _this;
  31179. var myAnySource = source;
  31180. myAnyThis._closePath = myAnySource._closePath;
  31181. myAnyThis._idx = myAnySource._idx;
  31182. myAnyThis.dashSize = myAnySource.dashSize;
  31183. myAnyThis.gapSize = myAnySource.gapSize;
  31184. myAnyThis.path3D = myAnySource.path3D;
  31185. myAnyThis.pathArray = myAnySource.pathArray;
  31186. myAnyThis.arc = myAnySource.arc;
  31187. myAnyThis.radius = myAnySource.radius;
  31188. // Animation ranges
  31189. if (_this._source._ranges) {
  31190. var ranges = _this._source._ranges;
  31191. for (var name in ranges) {
  31192. if (!ranges.hasOwnProperty(name)) {
  31193. continue;
  31194. }
  31195. if (!ranges[name]) {
  31196. continue;
  31197. }
  31198. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31199. }
  31200. }
  31201. // Metadata
  31202. if (source.metadata && source.metadata.clone) {
  31203. _this.metadata = source.metadata.clone();
  31204. }
  31205. else {
  31206. _this.metadata = source.metadata;
  31207. }
  31208. // Tags
  31209. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31210. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31211. }
  31212. // Parent
  31213. _this.parent = source.parent;
  31214. // Pivot
  31215. _this.setPivotMatrix(source.getPivotMatrix());
  31216. _this.id = name + "." + source.id;
  31217. // Material
  31218. _this.material = source.material;
  31219. var index;
  31220. if (!doNotCloneChildren) {
  31221. // Children
  31222. var directDescendants = source.getDescendants(true);
  31223. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31224. var child = directDescendants[index_1];
  31225. if (child.clone) {
  31226. child.clone(name + "." + child.name, _this);
  31227. }
  31228. }
  31229. }
  31230. // Physics clone
  31231. var physicsEngine = _this.getScene().getPhysicsEngine();
  31232. if (clonePhysicsImpostor && physicsEngine) {
  31233. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31234. if (impostor) {
  31235. _this.physicsImpostor = impostor.clone(_this);
  31236. }
  31237. }
  31238. // Particles
  31239. for (index = 0; index < scene.particleSystems.length; index++) {
  31240. var system = scene.particleSystems[index];
  31241. if (system.emitter === source) {
  31242. system.clone(system.name, _this);
  31243. }
  31244. }
  31245. _this.refreshBoundingInfo();
  31246. _this.computeWorldMatrix(true);
  31247. }
  31248. // Parent
  31249. if (parent !== null) {
  31250. _this.parent = parent;
  31251. }
  31252. return _this;
  31253. }
  31254. Object.defineProperty(Mesh, "FRONTSIDE", {
  31255. /**
  31256. * Mesh side orientation : usually the external or front surface
  31257. */
  31258. get: function () {
  31259. return Mesh._FRONTSIDE;
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. Object.defineProperty(Mesh, "BACKSIDE", {
  31265. /**
  31266. * Mesh side orientation : usually the internal or back surface
  31267. */
  31268. get: function () {
  31269. return Mesh._BACKSIDE;
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31275. /**
  31276. * Mesh side orientation : both internal and external or front and back surfaces
  31277. */
  31278. get: function () {
  31279. return Mesh._DOUBLESIDE;
  31280. },
  31281. enumerable: true,
  31282. configurable: true
  31283. });
  31284. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31285. /**
  31286. * Mesh side orientation : by default, `FRONTSIDE`
  31287. */
  31288. get: function () {
  31289. return Mesh._DEFAULTSIDE;
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. Object.defineProperty(Mesh, "NO_CAP", {
  31295. /**
  31296. * Mesh cap setting : no cap
  31297. */
  31298. get: function () {
  31299. return Mesh._NO_CAP;
  31300. },
  31301. enumerable: true,
  31302. configurable: true
  31303. });
  31304. Object.defineProperty(Mesh, "CAP_START", {
  31305. /**
  31306. * Mesh cap setting : one cap at the beginning of the mesh
  31307. */
  31308. get: function () {
  31309. return Mesh._CAP_START;
  31310. },
  31311. enumerable: true,
  31312. configurable: true
  31313. });
  31314. Object.defineProperty(Mesh, "CAP_END", {
  31315. /**
  31316. * Mesh cap setting : one cap at the end of the mesh
  31317. */
  31318. get: function () {
  31319. return Mesh._CAP_END;
  31320. },
  31321. enumerable: true,
  31322. configurable: true
  31323. });
  31324. Object.defineProperty(Mesh, "CAP_ALL", {
  31325. /**
  31326. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31327. */
  31328. get: function () {
  31329. return Mesh._CAP_ALL;
  31330. },
  31331. enumerable: true,
  31332. configurable: true
  31333. });
  31334. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31335. /**
  31336. * An event triggered before rendering the mesh
  31337. */
  31338. get: function () {
  31339. if (!this._onBeforeRenderObservable) {
  31340. this._onBeforeRenderObservable = new BABYLON.Observable();
  31341. }
  31342. return this._onBeforeRenderObservable;
  31343. },
  31344. enumerable: true,
  31345. configurable: true
  31346. });
  31347. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31348. /**
  31349. * An event triggered after rendering the mesh
  31350. */
  31351. get: function () {
  31352. if (!this._onAfterRenderObservable) {
  31353. this._onAfterRenderObservable = new BABYLON.Observable();
  31354. }
  31355. return this._onAfterRenderObservable;
  31356. },
  31357. enumerable: true,
  31358. configurable: true
  31359. });
  31360. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31361. /**
  31362. * An event triggered before drawing the mesh
  31363. */
  31364. get: function () {
  31365. if (!this._onBeforeDrawObservable) {
  31366. this._onBeforeDrawObservable = new BABYLON.Observable();
  31367. }
  31368. return this._onBeforeDrawObservable;
  31369. },
  31370. enumerable: true,
  31371. configurable: true
  31372. });
  31373. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31374. set: function (callback) {
  31375. if (this._onBeforeDrawObserver) {
  31376. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31377. }
  31378. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31379. },
  31380. enumerable: true,
  31381. configurable: true
  31382. });
  31383. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31384. get: function () {
  31385. return this._morphTargetManager;
  31386. },
  31387. set: function (value) {
  31388. if (this._morphTargetManager === value) {
  31389. return;
  31390. }
  31391. this._morphTargetManager = value;
  31392. this._syncGeometryWithMorphTargetManager();
  31393. },
  31394. enumerable: true,
  31395. configurable: true
  31396. });
  31397. Object.defineProperty(Mesh.prototype, "source", {
  31398. get: function () {
  31399. return this._source;
  31400. },
  31401. enumerable: true,
  31402. configurable: true
  31403. });
  31404. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31405. get: function () {
  31406. return this._unIndexed;
  31407. },
  31408. set: function (value) {
  31409. if (this._unIndexed !== value) {
  31410. this._unIndexed = value;
  31411. this._markSubMeshesAsAttributesDirty();
  31412. }
  31413. },
  31414. enumerable: true,
  31415. configurable: true
  31416. });
  31417. // Methods
  31418. /**
  31419. * Returns the string "Mesh".
  31420. */
  31421. Mesh.prototype.getClassName = function () {
  31422. return "Mesh";
  31423. };
  31424. /**
  31425. * Returns a string.
  31426. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31427. */
  31428. Mesh.prototype.toString = function (fullDetails) {
  31429. var ret = _super.prototype.toString.call(this, fullDetails);
  31430. ret += ", n vertices: " + this.getTotalVertices();
  31431. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31432. if (this.animations) {
  31433. for (var i = 0; i < this.animations.length; i++) {
  31434. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31435. }
  31436. }
  31437. if (fullDetails) {
  31438. if (this._geometry) {
  31439. var ib = this.getIndices();
  31440. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31441. if (vb && ib) {
  31442. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31443. }
  31444. }
  31445. else {
  31446. ret += ", flat shading: UNKNOWN";
  31447. }
  31448. }
  31449. return ret;
  31450. };
  31451. /** @hidden */
  31452. Mesh.prototype._unBindEffect = function () {
  31453. _super.prototype._unBindEffect.call(this);
  31454. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31455. var instance = _a[_i];
  31456. instance._unBindEffect();
  31457. }
  31458. };
  31459. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31460. /**
  31461. * True if the mesh has some Levels Of Details (LOD).
  31462. * Returns a boolean.
  31463. */
  31464. get: function () {
  31465. return this._LODLevels.length > 0;
  31466. },
  31467. enumerable: true,
  31468. configurable: true
  31469. });
  31470. /**
  31471. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31472. * @returns an array of {BABYLON.MeshLODLevel}
  31473. */
  31474. Mesh.prototype.getLODLevels = function () {
  31475. return this._LODLevels;
  31476. };
  31477. Mesh.prototype._sortLODLevels = function () {
  31478. this._LODLevels.sort(function (a, b) {
  31479. if (a.distance < b.distance) {
  31480. return 1;
  31481. }
  31482. if (a.distance > b.distance) {
  31483. return -1;
  31484. }
  31485. return 0;
  31486. });
  31487. };
  31488. /**
  31489. * Add a mesh as LOD level triggered at the given distance.
  31490. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31491. * @param distance The distance from the center of the object to show this level
  31492. * @param mesh The mesh to be added as LOD level (can be null)
  31493. * @return This mesh (for chaining)
  31494. */
  31495. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31496. if (mesh && mesh._masterMesh) {
  31497. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31498. return this;
  31499. }
  31500. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31501. this._LODLevels.push(level);
  31502. if (mesh) {
  31503. mesh._masterMesh = this;
  31504. }
  31505. this._sortLODLevels();
  31506. return this;
  31507. };
  31508. /**
  31509. * Returns the LOD level mesh at the passed distance or null if not found.
  31510. * It is related to the method `addLODLevel(distance, mesh)`.
  31511. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31512. * Returns an object Mesh or `null`.
  31513. */
  31514. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31515. for (var index = 0; index < this._LODLevels.length; index++) {
  31516. var level = this._LODLevels[index];
  31517. if (level.distance === distance) {
  31518. return level.mesh;
  31519. }
  31520. }
  31521. return null;
  31522. };
  31523. /**
  31524. * Remove a mesh from the LOD array
  31525. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31526. * @param {Mesh} mesh The mesh to be removed.
  31527. * @return {Mesh} This mesh (for chaining)
  31528. */
  31529. Mesh.prototype.removeLODLevel = function (mesh) {
  31530. for (var index = 0; index < this._LODLevels.length; index++) {
  31531. if (this._LODLevels[index].mesh === mesh) {
  31532. this._LODLevels.splice(index, 1);
  31533. if (mesh) {
  31534. mesh._masterMesh = null;
  31535. }
  31536. }
  31537. }
  31538. this._sortLODLevels();
  31539. return this;
  31540. };
  31541. /**
  31542. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31543. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31544. */
  31545. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31546. if (!this._LODLevels || this._LODLevels.length === 0) {
  31547. return this;
  31548. }
  31549. var bSphere;
  31550. if (boundingSphere) {
  31551. bSphere = boundingSphere;
  31552. }
  31553. else {
  31554. var boundingInfo = this.getBoundingInfo();
  31555. bSphere = boundingInfo.boundingSphere;
  31556. }
  31557. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31558. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31559. if (this.onLODLevelSelection) {
  31560. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31561. }
  31562. return this;
  31563. }
  31564. for (var index = 0; index < this._LODLevels.length; index++) {
  31565. var level = this._LODLevels[index];
  31566. if (level.distance < distanceToCamera) {
  31567. if (level.mesh) {
  31568. level.mesh._preActivate();
  31569. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31570. }
  31571. if (this.onLODLevelSelection) {
  31572. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31573. }
  31574. return level.mesh;
  31575. }
  31576. }
  31577. if (this.onLODLevelSelection) {
  31578. this.onLODLevelSelection(distanceToCamera, this, this);
  31579. }
  31580. return this;
  31581. };
  31582. Object.defineProperty(Mesh.prototype, "geometry", {
  31583. /**
  31584. * Returns the mesh internal Geometry object.
  31585. */
  31586. get: function () {
  31587. return this._geometry;
  31588. },
  31589. enumerable: true,
  31590. configurable: true
  31591. });
  31592. /**
  31593. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31594. */
  31595. Mesh.prototype.getTotalVertices = function () {
  31596. if (this._geometry === null || this._geometry === undefined) {
  31597. return 0;
  31598. }
  31599. return this._geometry.getTotalVertices();
  31600. };
  31601. /**
  31602. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31603. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31604. * You can force the copy with forceCopy === true
  31605. * Returns null if the mesh has no geometry or no vertex buffer.
  31606. * Possible `kind` values :
  31607. * - BABYLON.VertexBuffer.PositionKind
  31608. * - BABYLON.VertexBuffer.UVKind
  31609. * - BABYLON.VertexBuffer.UV2Kind
  31610. * - BABYLON.VertexBuffer.UV3Kind
  31611. * - BABYLON.VertexBuffer.UV4Kind
  31612. * - BABYLON.VertexBuffer.UV5Kind
  31613. * - BABYLON.VertexBuffer.UV6Kind
  31614. * - BABYLON.VertexBuffer.ColorKind
  31615. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31616. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31617. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31618. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31619. */
  31620. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31621. if (!this._geometry) {
  31622. return null;
  31623. }
  31624. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31625. };
  31626. /**
  31627. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31628. * Returns `null` if the mesh has no geometry.
  31629. * Possible `kind` values :
  31630. * - BABYLON.VertexBuffer.PositionKind
  31631. * - BABYLON.VertexBuffer.UVKind
  31632. * - BABYLON.VertexBuffer.UV2Kind
  31633. * - BABYLON.VertexBuffer.UV3Kind
  31634. * - BABYLON.VertexBuffer.UV4Kind
  31635. * - BABYLON.VertexBuffer.UV5Kind
  31636. * - BABYLON.VertexBuffer.UV6Kind
  31637. * - BABYLON.VertexBuffer.ColorKind
  31638. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31639. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31640. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31641. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31642. */
  31643. Mesh.prototype.getVertexBuffer = function (kind) {
  31644. if (!this._geometry) {
  31645. return null;
  31646. }
  31647. return this._geometry.getVertexBuffer(kind);
  31648. };
  31649. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31650. if (!this._geometry) {
  31651. if (this._delayInfo) {
  31652. return this._delayInfo.indexOf(kind) !== -1;
  31653. }
  31654. return false;
  31655. }
  31656. return this._geometry.isVerticesDataPresent(kind);
  31657. };
  31658. /**
  31659. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31660. * Possible `kind` values :
  31661. * - BABYLON.VertexBuffer.PositionKind
  31662. * - BABYLON.VertexBuffer.UVKind
  31663. * - BABYLON.VertexBuffer.UV2Kind
  31664. * - BABYLON.VertexBuffer.UV3Kind
  31665. * - BABYLON.VertexBuffer.UV4Kind
  31666. * - BABYLON.VertexBuffer.UV5Kind
  31667. * - BABYLON.VertexBuffer.UV6Kind
  31668. * - BABYLON.VertexBuffer.ColorKind
  31669. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31670. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31671. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31672. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31673. */
  31674. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31675. if (!this._geometry) {
  31676. if (this._delayInfo) {
  31677. return this._delayInfo.indexOf(kind) !== -1;
  31678. }
  31679. return false;
  31680. }
  31681. return this._geometry.isVertexBufferUpdatable(kind);
  31682. };
  31683. /**
  31684. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31685. * Possible `kind` values :
  31686. * - BABYLON.VertexBuffer.PositionKind
  31687. * - BABYLON.VertexBuffer.UVKind
  31688. * - BABYLON.VertexBuffer.UV2Kind
  31689. * - BABYLON.VertexBuffer.UV3Kind
  31690. * - BABYLON.VertexBuffer.UV4Kind
  31691. * - BABYLON.VertexBuffer.UV5Kind
  31692. * - BABYLON.VertexBuffer.UV6Kind
  31693. * - BABYLON.VertexBuffer.ColorKind
  31694. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31695. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31696. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31697. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31698. */
  31699. Mesh.prototype.getVerticesDataKinds = function () {
  31700. if (!this._geometry) {
  31701. var result = new Array();
  31702. if (this._delayInfo) {
  31703. this._delayInfo.forEach(function (kind, index, array) {
  31704. result.push(kind);
  31705. });
  31706. }
  31707. return result;
  31708. }
  31709. return this._geometry.getVerticesDataKinds();
  31710. };
  31711. /**
  31712. * Returns a positive integer : the total number of indices in this mesh geometry.
  31713. * Returns zero if the mesh has no geometry.
  31714. */
  31715. Mesh.prototype.getTotalIndices = function () {
  31716. if (!this._geometry) {
  31717. return 0;
  31718. }
  31719. return this._geometry.getTotalIndices();
  31720. };
  31721. /**
  31722. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31723. * @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.
  31724. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31725. * @returns the indices array or an empty array if the mesh has no geometry
  31726. */
  31727. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31728. if (!this._geometry) {
  31729. return [];
  31730. }
  31731. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31732. };
  31733. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31734. get: function () {
  31735. return this._masterMesh !== null && this._masterMesh !== undefined;
  31736. },
  31737. enumerable: true,
  31738. configurable: true
  31739. });
  31740. /**
  31741. * Determine if the current mesh is ready to be rendered
  31742. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31743. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31744. * @returns true if all associated assets are ready (material, textures, shaders)
  31745. */
  31746. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31747. if (completeCheck === void 0) { completeCheck = false; }
  31748. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31749. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31750. return false;
  31751. }
  31752. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31753. return false;
  31754. }
  31755. if (!this.subMeshes || this.subMeshes.length === 0) {
  31756. return true;
  31757. }
  31758. if (!completeCheck) {
  31759. return true;
  31760. }
  31761. var engine = this.getEngine();
  31762. var scene = this.getScene();
  31763. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31764. this.computeWorldMatrix();
  31765. var mat = this.material || scene.defaultMaterial;
  31766. if (mat) {
  31767. if (mat.storeEffectOnSubMeshes) {
  31768. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31769. var subMesh = _a[_i];
  31770. var effectiveMaterial = subMesh.getMaterial();
  31771. if (effectiveMaterial) {
  31772. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31773. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31774. return false;
  31775. }
  31776. }
  31777. else {
  31778. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31779. return false;
  31780. }
  31781. }
  31782. }
  31783. }
  31784. }
  31785. else {
  31786. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31787. return false;
  31788. }
  31789. }
  31790. }
  31791. // Shadows
  31792. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31793. var light = _c[_b];
  31794. var generator = light.getShadowGenerator();
  31795. if (generator) {
  31796. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31797. var subMesh = _e[_d];
  31798. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31799. return false;
  31800. }
  31801. }
  31802. }
  31803. }
  31804. // LOD
  31805. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31806. var lod = _g[_f];
  31807. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31808. return false;
  31809. }
  31810. }
  31811. return true;
  31812. };
  31813. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31814. /**
  31815. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31816. * This property is pertinent only for updatable parametric shapes.
  31817. */
  31818. get: function () {
  31819. return this._areNormalsFrozen;
  31820. },
  31821. enumerable: true,
  31822. configurable: true
  31823. });
  31824. /**
  31825. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31826. * It has no effect at all on other shapes.
  31827. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31828. * Returns the Mesh.
  31829. */
  31830. Mesh.prototype.freezeNormals = function () {
  31831. this._areNormalsFrozen = true;
  31832. return this;
  31833. };
  31834. /**
  31835. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31836. * It has no effect at all on other shapes.
  31837. * It reactivates the mesh normals computation if it was previously frozen.
  31838. * Returns the Mesh.
  31839. */
  31840. Mesh.prototype.unfreezeNormals = function () {
  31841. this._areNormalsFrozen = false;
  31842. return this;
  31843. };
  31844. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31845. /**
  31846. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31847. */
  31848. set: function (count) {
  31849. this._overridenInstanceCount = count;
  31850. },
  31851. enumerable: true,
  31852. configurable: true
  31853. });
  31854. // Methods
  31855. /** @hidden */
  31856. Mesh.prototype._preActivate = function () {
  31857. var sceneRenderId = this.getScene().getRenderId();
  31858. if (this._preActivateId === sceneRenderId) {
  31859. return this;
  31860. }
  31861. this._preActivateId = sceneRenderId;
  31862. this._visibleInstances = null;
  31863. return this;
  31864. };
  31865. /** @hidden */
  31866. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31867. if (this._visibleInstances) {
  31868. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31869. }
  31870. return this;
  31871. };
  31872. /** @hidden */
  31873. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31874. if (!this._visibleInstances) {
  31875. this._visibleInstances = {};
  31876. this._visibleInstances.defaultRenderId = renderId;
  31877. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31878. }
  31879. if (!this._visibleInstances[renderId]) {
  31880. this._visibleInstances[renderId] = new Array();
  31881. }
  31882. this._visibleInstances[renderId].push(instance);
  31883. return this;
  31884. };
  31885. /**
  31886. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31887. * This means the mesh underlying bounding box and sphere are recomputed.
  31888. * Returns the Mesh.
  31889. */
  31890. Mesh.prototype.refreshBoundingInfo = function () {
  31891. return this._refreshBoundingInfo(false);
  31892. };
  31893. /** @hidden */
  31894. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31895. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31896. return this;
  31897. }
  31898. var data = this._getPositionData(applySkeleton);
  31899. if (data) {
  31900. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31901. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31902. }
  31903. if (this.subMeshes) {
  31904. for (var index = 0; index < this.subMeshes.length; index++) {
  31905. this.subMeshes[index].refreshBoundingInfo();
  31906. }
  31907. }
  31908. this._updateBoundingInfo();
  31909. return this;
  31910. };
  31911. Mesh.prototype._getPositionData = function (applySkeleton) {
  31912. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31913. if (data && applySkeleton && this.skeleton) {
  31914. data = BABYLON.Tools.Slice(data);
  31915. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31916. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31917. if (matricesWeightsData && matricesIndicesData) {
  31918. var needExtras = this.numBoneInfluencers > 4;
  31919. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31920. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31921. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31922. var tempVector = BABYLON.Tmp.Vector3[0];
  31923. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31924. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31925. var matWeightIdx = 0;
  31926. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31927. finalMatrix.reset();
  31928. var inf;
  31929. var weight;
  31930. for (inf = 0; inf < 4; inf++) {
  31931. weight = matricesWeightsData[matWeightIdx + inf];
  31932. if (weight > 0) {
  31933. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31934. finalMatrix.addToSelf(tempMatrix);
  31935. }
  31936. }
  31937. if (needExtras) {
  31938. for (inf = 0; inf < 4; inf++) {
  31939. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31940. if (weight > 0) {
  31941. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31942. finalMatrix.addToSelf(tempMatrix);
  31943. }
  31944. }
  31945. }
  31946. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31947. tempVector.toArray(data, index);
  31948. }
  31949. }
  31950. }
  31951. return data;
  31952. };
  31953. /** @hidden */
  31954. Mesh.prototype._createGlobalSubMesh = function (force) {
  31955. var totalVertices = this.getTotalVertices();
  31956. if (!totalVertices || !this.getIndices()) {
  31957. return null;
  31958. }
  31959. // Check if we need to recreate the submeshes
  31960. if (this.subMeshes && this.subMeshes.length > 0) {
  31961. var ib = this.getIndices();
  31962. if (!ib) {
  31963. return null;
  31964. }
  31965. var totalIndices = ib.length;
  31966. var needToRecreate = false;
  31967. if (force) {
  31968. needToRecreate = true;
  31969. }
  31970. else {
  31971. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31972. var submesh = _a[_i];
  31973. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31974. needToRecreate = true;
  31975. break;
  31976. }
  31977. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31978. needToRecreate = true;
  31979. break;
  31980. }
  31981. }
  31982. }
  31983. if (!needToRecreate) {
  31984. return this.subMeshes[0];
  31985. }
  31986. }
  31987. this.releaseSubMeshes();
  31988. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31989. };
  31990. Mesh.prototype.subdivide = function (count) {
  31991. if (count < 1) {
  31992. return;
  31993. }
  31994. var totalIndices = this.getTotalIndices();
  31995. var subdivisionSize = (totalIndices / count) | 0;
  31996. var offset = 0;
  31997. // Ensure that subdivisionSize is a multiple of 3
  31998. while (subdivisionSize % 3 !== 0) {
  31999. subdivisionSize++;
  32000. }
  32001. this.releaseSubMeshes();
  32002. for (var index = 0; index < count; index++) {
  32003. if (offset >= totalIndices) {
  32004. break;
  32005. }
  32006. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32007. offset += subdivisionSize;
  32008. }
  32009. this.synchronizeInstances();
  32010. };
  32011. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32012. if (updatable === void 0) { updatable = false; }
  32013. if (!this._geometry) {
  32014. var vertexData = new BABYLON.VertexData();
  32015. vertexData.set(data, kind);
  32016. var scene = this.getScene();
  32017. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32018. }
  32019. else {
  32020. this._geometry.setVerticesData(kind, data, updatable, stride);
  32021. }
  32022. return this;
  32023. };
  32024. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32025. if (updatable === void 0) { updatable = true; }
  32026. var vb = this.getVertexBuffer(kind);
  32027. if (!vb || vb.isUpdatable() === updatable) {
  32028. return;
  32029. }
  32030. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32031. };
  32032. /**
  32033. * Sets the mesh VertexBuffer.
  32034. * Returns the Mesh.
  32035. */
  32036. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32037. if (!this._geometry) {
  32038. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32039. }
  32040. this._geometry.setVerticesBuffer(buffer);
  32041. return this;
  32042. };
  32043. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32044. if (!this._geometry) {
  32045. return this;
  32046. }
  32047. if (!makeItUnique) {
  32048. this._geometry.updateVerticesData(kind, data, updateExtends);
  32049. }
  32050. else {
  32051. this.makeGeometryUnique();
  32052. this.updateVerticesData(kind, data, updateExtends, false);
  32053. }
  32054. return this;
  32055. };
  32056. /**
  32057. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32058. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32059. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32060. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32061. * Returns the Mesh.
  32062. */
  32063. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32064. if (computeNormals === void 0) { computeNormals = true; }
  32065. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32066. if (!positions) {
  32067. return this;
  32068. }
  32069. positionFunction(positions);
  32070. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32071. if (computeNormals) {
  32072. var indices = this.getIndices();
  32073. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32074. if (!normals) {
  32075. return this;
  32076. }
  32077. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32078. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32079. }
  32080. return this;
  32081. };
  32082. /**
  32083. * Creates a un-shared specific occurence of the geometry for the mesh.
  32084. * Returns the Mesh.
  32085. */
  32086. Mesh.prototype.makeGeometryUnique = function () {
  32087. if (!this._geometry) {
  32088. return this;
  32089. }
  32090. var oldGeometry = this._geometry;
  32091. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32092. oldGeometry.releaseForMesh(this, true);
  32093. geometry.applyToMesh(this);
  32094. return this;
  32095. };
  32096. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32097. if (totalVertices === void 0) { totalVertices = null; }
  32098. if (updatable === void 0) { updatable = false; }
  32099. if (!this._geometry) {
  32100. var vertexData = new BABYLON.VertexData();
  32101. vertexData.indices = indices;
  32102. var scene = this.getScene();
  32103. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32104. }
  32105. else {
  32106. this._geometry.setIndices(indices, totalVertices, updatable);
  32107. }
  32108. return this;
  32109. };
  32110. /**
  32111. * Update the current index buffer
  32112. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32113. * Returns the Mesh.
  32114. */
  32115. Mesh.prototype.updateIndices = function (indices, offset) {
  32116. if (!this._geometry) {
  32117. return this;
  32118. }
  32119. this._geometry.updateIndices(indices, offset);
  32120. return this;
  32121. };
  32122. /**
  32123. * Invert the geometry to move from a right handed system to a left handed one.
  32124. * Returns the Mesh.
  32125. */
  32126. Mesh.prototype.toLeftHanded = function () {
  32127. if (!this._geometry) {
  32128. return this;
  32129. }
  32130. this._geometry.toLeftHanded();
  32131. return this;
  32132. };
  32133. /** @hidden */
  32134. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32135. if (!this._geometry) {
  32136. return this;
  32137. }
  32138. var engine = this.getScene().getEngine();
  32139. // Wireframe
  32140. var indexToBind;
  32141. if (this._unIndexed) {
  32142. indexToBind = null;
  32143. }
  32144. else {
  32145. switch (fillMode) {
  32146. case BABYLON.Material.PointFillMode:
  32147. indexToBind = null;
  32148. break;
  32149. case BABYLON.Material.WireFrameFillMode:
  32150. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32151. break;
  32152. default:
  32153. case BABYLON.Material.TriangleFillMode:
  32154. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32155. break;
  32156. }
  32157. }
  32158. // VBOs
  32159. this._geometry._bind(effect, indexToBind);
  32160. return this;
  32161. };
  32162. /** @hidden */
  32163. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32164. if (alternate === void 0) { alternate = false; }
  32165. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32166. return this;
  32167. }
  32168. if (this._onBeforeDrawObservable) {
  32169. this._onBeforeDrawObservable.notifyObservers(this);
  32170. }
  32171. var scene = this.getScene();
  32172. var engine = scene.getEngine();
  32173. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32174. // or triangles as points
  32175. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32176. }
  32177. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32178. // Triangles as wireframe
  32179. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32180. }
  32181. else {
  32182. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32183. }
  32184. if (scene._isAlternateRenderingEnabled && !alternate) {
  32185. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32186. if (!effect || !scene.activeCamera) {
  32187. return this;
  32188. }
  32189. scene._switchToAlternateCameraConfiguration(true);
  32190. this._effectiveMaterial.bindView(effect);
  32191. this._effectiveMaterial.bindViewProjection(effect);
  32192. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32193. this._draw(subMesh, fillMode, instancesCount, true);
  32194. engine.setViewport(scene.activeCamera.viewport);
  32195. scene._switchToAlternateCameraConfiguration(false);
  32196. this._effectiveMaterial.bindView(effect);
  32197. this._effectiveMaterial.bindViewProjection(effect);
  32198. }
  32199. return this;
  32200. };
  32201. /**
  32202. * Registers for this mesh a javascript function called just before the rendering process.
  32203. * This function is passed the current mesh.
  32204. * Return the Mesh.
  32205. */
  32206. Mesh.prototype.registerBeforeRender = function (func) {
  32207. this.onBeforeRenderObservable.add(func);
  32208. return this;
  32209. };
  32210. /**
  32211. * Disposes a previously registered javascript function called before the rendering.
  32212. * This function is passed the current mesh.
  32213. * Returns the Mesh.
  32214. */
  32215. Mesh.prototype.unregisterBeforeRender = function (func) {
  32216. this.onBeforeRenderObservable.removeCallback(func);
  32217. return this;
  32218. };
  32219. /**
  32220. * Registers for this mesh a javascript function called just after the rendering is complete.
  32221. * This function is passed the current mesh.
  32222. * Returns the Mesh.
  32223. */
  32224. Mesh.prototype.registerAfterRender = function (func) {
  32225. this.onAfterRenderObservable.add(func);
  32226. return this;
  32227. };
  32228. /**
  32229. * Disposes a previously registered javascript function called after the rendering.
  32230. * This function is passed the current mesh.
  32231. * Return the Mesh.
  32232. */
  32233. Mesh.prototype.unregisterAfterRender = function (func) {
  32234. this.onAfterRenderObservable.removeCallback(func);
  32235. return this;
  32236. };
  32237. /** @hidden */
  32238. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32239. var scene = this.getScene();
  32240. this._batchCache.mustReturn = false;
  32241. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32242. this._batchCache.visibleInstances[subMeshId] = null;
  32243. if (this._visibleInstances) {
  32244. var currentRenderId = scene.getRenderId();
  32245. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32246. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32247. var selfRenderId = this._renderId;
  32248. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32249. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32250. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32251. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32252. }
  32253. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32254. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32255. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32256. this._batchCache.mustReturn = true;
  32257. return this._batchCache;
  32258. }
  32259. if (currentRenderId !== selfRenderId) {
  32260. this._batchCache.renderSelf[subMeshId] = false;
  32261. }
  32262. }
  32263. this._renderIdForInstances[subMeshId] = currentRenderId;
  32264. }
  32265. return this._batchCache;
  32266. };
  32267. /** @hidden */
  32268. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32269. var visibleInstances = batch.visibleInstances[subMesh._id];
  32270. if (!visibleInstances) {
  32271. return this;
  32272. }
  32273. var matricesCount = visibleInstances.length + 1;
  32274. var bufferSize = matricesCount * 16 * 4;
  32275. var currentInstancesBufferSize = this._instancesBufferSize;
  32276. var instancesBuffer = this._instancesBuffer;
  32277. while (this._instancesBufferSize < bufferSize) {
  32278. this._instancesBufferSize *= 2;
  32279. }
  32280. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32281. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32282. }
  32283. var offset = 0;
  32284. var instancesCount = 0;
  32285. var world = this.getWorldMatrix();
  32286. if (batch.renderSelf[subMesh._id]) {
  32287. world.copyToArray(this._instancesData, offset);
  32288. offset += 16;
  32289. instancesCount++;
  32290. }
  32291. if (visibleInstances) {
  32292. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32293. var instance = visibleInstances[instanceIndex];
  32294. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32295. offset += 16;
  32296. instancesCount++;
  32297. }
  32298. }
  32299. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32300. if (instancesBuffer) {
  32301. instancesBuffer.dispose();
  32302. }
  32303. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32304. this._instancesBuffer = instancesBuffer;
  32305. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32306. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32307. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32308. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32309. }
  32310. else {
  32311. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32312. }
  32313. this._bind(subMesh, effect, fillMode);
  32314. this._draw(subMesh, fillMode, instancesCount);
  32315. engine.unbindInstanceAttributes();
  32316. return this;
  32317. };
  32318. /** @hidden */
  32319. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32320. var scene = this.getScene();
  32321. var engine = scene.getEngine();
  32322. if (hardwareInstancedRendering) {
  32323. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32324. }
  32325. else {
  32326. if (batch.renderSelf[subMesh._id]) {
  32327. // Draw
  32328. if (onBeforeDraw) {
  32329. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32330. }
  32331. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32332. }
  32333. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32334. if (visibleInstancesForSubMesh) {
  32335. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32336. var instance = visibleInstancesForSubMesh[instanceIndex];
  32337. // World
  32338. var world = instance.getWorldMatrix();
  32339. if (onBeforeDraw) {
  32340. onBeforeDraw(true, world, effectiveMaterial);
  32341. }
  32342. // Draw
  32343. this._draw(subMesh, fillMode);
  32344. }
  32345. }
  32346. }
  32347. return this;
  32348. };
  32349. /**
  32350. * 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
  32351. * @param subMesh defines the subMesh to render
  32352. * @param enableAlphaMode defines if alpha mode can be changed
  32353. * @returns the current mesh
  32354. */
  32355. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32356. this._checkOcclusionQuery();
  32357. if (this._isOccluded) {
  32358. return this;
  32359. }
  32360. var scene = this.getScene();
  32361. // Managing instances
  32362. var batch = this._getInstancesRenderList(subMesh._id);
  32363. if (batch.mustReturn) {
  32364. return this;
  32365. }
  32366. // Checking geometry state
  32367. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32368. return this;
  32369. }
  32370. if (this._onBeforeRenderObservable) {
  32371. this._onBeforeRenderObservable.notifyObservers(this);
  32372. }
  32373. var engine = scene.getEngine();
  32374. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32375. // Material
  32376. var material = subMesh.getMaterial();
  32377. if (!material) {
  32378. return this;
  32379. }
  32380. this._effectiveMaterial = material;
  32381. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32382. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32383. return this;
  32384. }
  32385. }
  32386. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32387. return this;
  32388. }
  32389. // Alpha mode
  32390. if (enableAlphaMode) {
  32391. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32392. }
  32393. // Outline - step 1
  32394. var savedDepthWrite = engine.getDepthWrite();
  32395. if (this.renderOutline) {
  32396. engine.setDepthWrite(false);
  32397. scene.getOutlineRenderer().render(subMesh, batch);
  32398. engine.setDepthWrite(savedDepthWrite);
  32399. }
  32400. var effect;
  32401. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32402. effect = subMesh.effect;
  32403. }
  32404. else {
  32405. effect = this._effectiveMaterial.getEffect();
  32406. }
  32407. if (!effect) {
  32408. return this;
  32409. }
  32410. var sideOrientation = this.overrideMaterialSideOrientation;
  32411. if (sideOrientation == null) {
  32412. sideOrientation = this._effectiveMaterial.sideOrientation;
  32413. if (this._getWorldMatrixDeterminant() < 0) {
  32414. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32415. }
  32416. }
  32417. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32418. if (this._effectiveMaterial.forceDepthWrite) {
  32419. engine.setDepthWrite(true);
  32420. }
  32421. // Bind
  32422. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32423. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32424. this._bind(subMesh, effect, fillMode);
  32425. }
  32426. var world = this.getWorldMatrix();
  32427. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32428. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32429. }
  32430. else {
  32431. this._effectiveMaterial.bind(world, this);
  32432. }
  32433. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32434. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32435. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32436. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32437. }
  32438. // Draw
  32439. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32440. // Unbind
  32441. this._effectiveMaterial.unbind();
  32442. // Outline - step 2
  32443. if (this.renderOutline && savedDepthWrite) {
  32444. engine.setDepthWrite(true);
  32445. engine.setColorWrite(false);
  32446. scene.getOutlineRenderer().render(subMesh, batch);
  32447. engine.setColorWrite(true);
  32448. }
  32449. // Overlay
  32450. if (this.renderOverlay) {
  32451. var currentMode = engine.getAlphaMode();
  32452. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32453. scene.getOutlineRenderer().render(subMesh, batch, true);
  32454. engine.setAlphaMode(currentMode);
  32455. }
  32456. if (this._onAfterRenderObservable) {
  32457. this._onAfterRenderObservable.notifyObservers(this);
  32458. }
  32459. return this;
  32460. };
  32461. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32462. if (isInstance && effectiveMaterial) {
  32463. effectiveMaterial.bindOnlyWorldMatrix(world);
  32464. }
  32465. };
  32466. /**
  32467. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32468. */
  32469. Mesh.prototype.getEmittedParticleSystems = function () {
  32470. var results = new Array();
  32471. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32472. var particleSystem = this.getScene().particleSystems[index];
  32473. if (particleSystem.emitter === this) {
  32474. results.push(particleSystem);
  32475. }
  32476. }
  32477. return results;
  32478. };
  32479. /**
  32480. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32481. */
  32482. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32483. var results = new Array();
  32484. var descendants = this.getDescendants();
  32485. descendants.push(this);
  32486. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32487. var particleSystem = this.getScene().particleSystems[index];
  32488. var emitter = particleSystem.emitter;
  32489. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32490. results.push(particleSystem);
  32491. }
  32492. }
  32493. return results;
  32494. };
  32495. /**
  32496. * Normalize matrix weights so that all vertices have a total weight set to 1
  32497. */
  32498. Mesh.prototype.cleanMatrixWeights = function () {
  32499. var epsilon = 1e-3;
  32500. var noInfluenceBoneIndex = 0.0;
  32501. if (this.skeleton) {
  32502. noInfluenceBoneIndex = this.skeleton.bones.length;
  32503. }
  32504. else {
  32505. return;
  32506. }
  32507. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32508. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32509. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32510. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32511. var influencers = this.numBoneInfluencers;
  32512. var size = matricesWeights.length;
  32513. for (var i = 0; i < size; i += 4) {
  32514. var weight = 0.0;
  32515. var firstZeroWeight = -1;
  32516. for (var j = 0; j < 4; j++) {
  32517. var w = matricesWeights[i + j];
  32518. weight += w;
  32519. if (w < epsilon && firstZeroWeight < 0) {
  32520. firstZeroWeight = j;
  32521. }
  32522. }
  32523. if (matricesWeightsExtra) {
  32524. for (var j = 0; j < 4; j++) {
  32525. var w = matricesWeightsExtra[i + j];
  32526. weight += w;
  32527. if (w < epsilon && firstZeroWeight < 0) {
  32528. firstZeroWeight = j + 4;
  32529. }
  32530. }
  32531. }
  32532. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32533. firstZeroWeight = influencers - 1;
  32534. }
  32535. if (weight > epsilon) {
  32536. var mweight = 1.0 / weight;
  32537. for (var j = 0; j < 4; j++) {
  32538. matricesWeights[i + j] *= mweight;
  32539. }
  32540. if (matricesWeightsExtra) {
  32541. for (var j = 0; j < 4; j++) {
  32542. matricesWeightsExtra[i + j] *= mweight;
  32543. }
  32544. }
  32545. }
  32546. else {
  32547. if (firstZeroWeight >= 4) {
  32548. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32549. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32550. }
  32551. else {
  32552. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32553. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32554. }
  32555. }
  32556. }
  32557. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32558. if (matricesIndicesExtra) {
  32559. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32560. }
  32561. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32562. if (matricesWeightsExtra) {
  32563. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32564. }
  32565. };
  32566. /** @hidden */
  32567. Mesh.prototype._checkDelayState = function () {
  32568. var scene = this.getScene();
  32569. if (this._geometry) {
  32570. this._geometry.load(scene);
  32571. }
  32572. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32574. this._queueLoad(scene);
  32575. }
  32576. return this;
  32577. };
  32578. Mesh.prototype._queueLoad = function (scene) {
  32579. var _this = this;
  32580. scene._addPendingData(this);
  32581. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32582. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32583. if (data instanceof ArrayBuffer) {
  32584. _this._delayLoadingFunction(data, _this);
  32585. }
  32586. else {
  32587. _this._delayLoadingFunction(JSON.parse(data), _this);
  32588. }
  32589. _this.instances.forEach(function (instance) {
  32590. instance._syncSubMeshes();
  32591. });
  32592. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32593. scene._removePendingData(_this);
  32594. }, function () { }, scene.database, getBinaryData);
  32595. return this;
  32596. };
  32597. /**
  32598. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32599. * A mesh is in the frustum if its bounding box intersects the frustum
  32600. * @param frustumPlanes defines the frustum to test
  32601. * @returns true if the mesh is in the frustum planes
  32602. */
  32603. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32604. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32605. return false;
  32606. }
  32607. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32608. return false;
  32609. }
  32610. this._checkDelayState();
  32611. return true;
  32612. };
  32613. /**
  32614. * Sets the mesh material by the material or multiMaterial `id` property.
  32615. * The material `id` is a string identifying the material or the multiMaterial.
  32616. * This method returns the Mesh.
  32617. */
  32618. Mesh.prototype.setMaterialByID = function (id) {
  32619. var materials = this.getScene().materials;
  32620. var index;
  32621. for (index = materials.length - 1; index > -1; index--) {
  32622. if (materials[index].id === id) {
  32623. this.material = materials[index];
  32624. return this;
  32625. }
  32626. }
  32627. // Multi
  32628. var multiMaterials = this.getScene().multiMaterials;
  32629. for (index = multiMaterials.length - 1; index > -1; index--) {
  32630. if (multiMaterials[index].id === id) {
  32631. this.material = multiMaterials[index];
  32632. return this;
  32633. }
  32634. }
  32635. return this;
  32636. };
  32637. /**
  32638. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32639. */
  32640. Mesh.prototype.getAnimatables = function () {
  32641. var results = new Array();
  32642. if (this.material) {
  32643. results.push(this.material);
  32644. }
  32645. if (this.skeleton) {
  32646. results.push(this.skeleton);
  32647. }
  32648. return results;
  32649. };
  32650. /**
  32651. * Modifies the mesh geometry according to the passed transformation matrix.
  32652. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32653. * The mesh normals are modified using the same transformation.
  32654. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32655. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32656. * Returns the Mesh.
  32657. */
  32658. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32659. // Position
  32660. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32661. return this;
  32662. }
  32663. var submeshes = this.subMeshes.splice(0);
  32664. this._resetPointsArrayCache();
  32665. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32666. var temp = new Array();
  32667. var index;
  32668. for (index = 0; index < data.length; index += 3) {
  32669. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32670. }
  32671. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32672. // Normals
  32673. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32674. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32675. temp = [];
  32676. for (index = 0; index < data.length; index += 3) {
  32677. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32678. }
  32679. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32680. }
  32681. // flip faces?
  32682. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32683. this.flipFaces();
  32684. }
  32685. // Restore submeshes
  32686. this.releaseSubMeshes();
  32687. this.subMeshes = submeshes;
  32688. return this;
  32689. };
  32690. /**
  32691. * Modifies the mesh geometry according to its own current World Matrix.
  32692. * The mesh World Matrix is then reset.
  32693. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32694. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32695. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32696. * Returns the Mesh.
  32697. */
  32698. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32699. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32700. this.scaling.copyFromFloats(1, 1, 1);
  32701. this.position.copyFromFloats(0, 0, 0);
  32702. this.rotation.copyFromFloats(0, 0, 0);
  32703. //only if quaternion is already set
  32704. if (this.rotationQuaternion) {
  32705. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32706. }
  32707. this._worldMatrix = BABYLON.Matrix.Identity();
  32708. return this;
  32709. };
  32710. Object.defineProperty(Mesh.prototype, "_positions", {
  32711. // Cache
  32712. get: function () {
  32713. if (this._geometry) {
  32714. return this._geometry._positions;
  32715. }
  32716. return null;
  32717. },
  32718. enumerable: true,
  32719. configurable: true
  32720. });
  32721. /** @hidden */
  32722. Mesh.prototype._resetPointsArrayCache = function () {
  32723. if (this._geometry) {
  32724. this._geometry._resetPointsArrayCache();
  32725. }
  32726. return this;
  32727. };
  32728. /** @hidden */
  32729. Mesh.prototype._generatePointsArray = function () {
  32730. if (this._geometry) {
  32731. return this._geometry._generatePointsArray();
  32732. }
  32733. return false;
  32734. };
  32735. /**
  32736. * Returns a new Mesh object generated from the current mesh properties.
  32737. * This method must not get confused with createInstance().
  32738. * The parameter `name` is a string, the name given to the new mesh.
  32739. * The optional parameter `newParent` can be any Node object (default `null`).
  32740. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32741. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32742. */
  32743. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32744. if (name === void 0) { name = ""; }
  32745. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32746. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32747. };
  32748. /**
  32749. * Releases resources associated with this mesh.
  32750. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32751. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32752. */
  32753. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32754. var _this = this;
  32755. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32756. this.morphTargetManager = null;
  32757. if (this._geometry) {
  32758. this._geometry.releaseForMesh(this, true);
  32759. }
  32760. if (this._onBeforeDrawObservable) {
  32761. this._onBeforeDrawObservable.clear();
  32762. }
  32763. if (this._onBeforeRenderObservable) {
  32764. this._onBeforeRenderObservable.clear();
  32765. }
  32766. if (this._onAfterRenderObservable) {
  32767. this._onAfterRenderObservable.clear();
  32768. }
  32769. // Sources
  32770. var meshes = this.getScene().meshes;
  32771. meshes.forEach(function (abstractMesh) {
  32772. var mesh = abstractMesh;
  32773. if (mesh._source && mesh._source === _this) {
  32774. mesh._source = null;
  32775. }
  32776. });
  32777. this._source = null;
  32778. // Instances
  32779. if (this._instancesBuffer) {
  32780. this._instancesBuffer.dispose();
  32781. this._instancesBuffer = null;
  32782. }
  32783. while (this.instances.length) {
  32784. this.instances[0].dispose();
  32785. }
  32786. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32787. };
  32788. /**
  32789. * Modifies the mesh geometry according to a displacement map.
  32790. * 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.
  32791. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32792. * This method returns nothing.
  32793. * @param url is a string, the URL from the image file is to be downloaded.
  32794. * @param minHeight is the lower limit of the displacement.
  32795. * @param maxHeight is the upper limit of the displacement.
  32796. * @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.
  32797. * @param uvOffset is an optional vector2 used to offset UV.
  32798. * @param uvScale is an optional vector2 used to scale UV.
  32799. * @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.
  32800. * @returns the Mesh.
  32801. */
  32802. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32803. var _this = this;
  32804. if (forceUpdate === void 0) { forceUpdate = false; }
  32805. var scene = this.getScene();
  32806. var onload = function (img) {
  32807. // Getting height map data
  32808. var canvas = document.createElement("canvas");
  32809. var context = canvas.getContext("2d");
  32810. var heightMapWidth = img.width;
  32811. var heightMapHeight = img.height;
  32812. canvas.width = heightMapWidth;
  32813. canvas.height = heightMapHeight;
  32814. context.drawImage(img, 0, 0);
  32815. // Create VertexData from map data
  32816. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32817. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32818. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32819. //execute success callback, if set
  32820. if (onSuccess) {
  32821. onSuccess(_this);
  32822. }
  32823. };
  32824. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32825. return this;
  32826. };
  32827. /**
  32828. * Modifies the mesh geometry according to a displacementMap buffer.
  32829. * 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.
  32830. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32831. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32832. * @param heightMapWidth is the width of the buffer image.
  32833. * @param heightMapHeight is the height of the buffer image.
  32834. * @param minHeight is the lower limit of the displacement.
  32835. * @param maxHeight is the upper limit of the displacement.
  32836. * @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.
  32837. * @param uvOffset is an optional vector2 used to offset UV.
  32838. * @param uvScale is an optional vector2 used to scale UV.
  32839. * @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.
  32840. * @returns the Mesh.
  32841. */
  32842. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32843. if (forceUpdate === void 0) { forceUpdate = false; }
  32844. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32845. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32846. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32847. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32848. return this;
  32849. }
  32850. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32851. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32852. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32853. var position = BABYLON.Vector3.Zero();
  32854. var normal = BABYLON.Vector3.Zero();
  32855. var uv = BABYLON.Vector2.Zero();
  32856. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32857. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32858. for (var index = 0; index < positions.length; index += 3) {
  32859. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32860. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32861. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32862. // Compute height
  32863. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32864. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32865. var pos = (u + v * heightMapWidth) * 4;
  32866. var r = buffer[pos] / 255.0;
  32867. var g = buffer[pos + 1] / 255.0;
  32868. var b = buffer[pos + 2] / 255.0;
  32869. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32870. normal.normalize();
  32871. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32872. position = position.add(normal);
  32873. position.toArray(positions, index);
  32874. }
  32875. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32876. if (forceUpdate) {
  32877. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32878. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32879. }
  32880. else {
  32881. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32882. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32883. }
  32884. return this;
  32885. };
  32886. /**
  32887. * Modify the mesh to get a flat shading rendering.
  32888. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32889. * This method returns the Mesh.
  32890. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32891. */
  32892. Mesh.prototype.convertToFlatShadedMesh = function () {
  32893. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32894. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32895. var kinds = this.getVerticesDataKinds();
  32896. var vbs = {};
  32897. var data = {};
  32898. var newdata = {};
  32899. var updatableNormals = false;
  32900. var kindIndex;
  32901. var kind;
  32902. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32903. kind = kinds[kindIndex];
  32904. var vertexBuffer = this.getVertexBuffer(kind);
  32905. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32906. updatableNormals = vertexBuffer.isUpdatable();
  32907. kinds.splice(kindIndex, 1);
  32908. kindIndex--;
  32909. continue;
  32910. }
  32911. vbs[kind] = vertexBuffer;
  32912. data[kind] = vbs[kind].getData();
  32913. newdata[kind] = [];
  32914. }
  32915. // Save previous submeshes
  32916. var previousSubmeshes = this.subMeshes.slice(0);
  32917. var indices = this.getIndices();
  32918. var totalIndices = this.getTotalIndices();
  32919. // Generating unique vertices per face
  32920. var index;
  32921. for (index = 0; index < totalIndices; index++) {
  32922. var vertexIndex = indices[index];
  32923. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32924. kind = kinds[kindIndex];
  32925. var stride = vbs[kind].getStrideSize();
  32926. for (var offset = 0; offset < stride; offset++) {
  32927. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32928. }
  32929. }
  32930. }
  32931. // Updating faces & normal
  32932. var normals = [];
  32933. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32934. for (index = 0; index < totalIndices; index += 3) {
  32935. indices[index] = index;
  32936. indices[index + 1] = index + 1;
  32937. indices[index + 2] = index + 2;
  32938. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32939. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32940. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32941. var p1p2 = p1.subtract(p2);
  32942. var p3p2 = p3.subtract(p2);
  32943. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32944. // Store same normals for every vertex
  32945. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32946. normals.push(normal.x);
  32947. normals.push(normal.y);
  32948. normals.push(normal.z);
  32949. }
  32950. }
  32951. this.setIndices(indices);
  32952. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32953. // Updating vertex buffers
  32954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32955. kind = kinds[kindIndex];
  32956. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32957. }
  32958. // Updating submeshes
  32959. this.releaseSubMeshes();
  32960. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32961. var previousOne = previousSubmeshes[submeshIndex];
  32962. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32963. }
  32964. this.synchronizeInstances();
  32965. return this;
  32966. };
  32967. /**
  32968. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32969. * In other words, more vertices, no more indices and a single bigger VBO.
  32970. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32971. * Returns the Mesh.
  32972. */
  32973. Mesh.prototype.convertToUnIndexedMesh = function () {
  32974. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32975. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32976. var kinds = this.getVerticesDataKinds();
  32977. var vbs = {};
  32978. var data = {};
  32979. var newdata = {};
  32980. var kindIndex;
  32981. var kind;
  32982. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32983. kind = kinds[kindIndex];
  32984. var vertexBuffer = this.getVertexBuffer(kind);
  32985. vbs[kind] = vertexBuffer;
  32986. data[kind] = vbs[kind].getData();
  32987. newdata[kind] = [];
  32988. }
  32989. // Save previous submeshes
  32990. var previousSubmeshes = this.subMeshes.slice(0);
  32991. var indices = this.getIndices();
  32992. var totalIndices = this.getTotalIndices();
  32993. // Generating unique vertices per face
  32994. var index;
  32995. for (index = 0; index < totalIndices; index++) {
  32996. var vertexIndex = indices[index];
  32997. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32998. kind = kinds[kindIndex];
  32999. var stride = vbs[kind].getStrideSize();
  33000. for (var offset = 0; offset < stride; offset++) {
  33001. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33002. }
  33003. }
  33004. }
  33005. // Updating indices
  33006. for (index = 0; index < totalIndices; index += 3) {
  33007. indices[index] = index;
  33008. indices[index + 1] = index + 1;
  33009. indices[index + 2] = index + 2;
  33010. }
  33011. this.setIndices(indices);
  33012. // Updating vertex buffers
  33013. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33014. kind = kinds[kindIndex];
  33015. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33016. }
  33017. // Updating submeshes
  33018. this.releaseSubMeshes();
  33019. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33020. var previousOne = previousSubmeshes[submeshIndex];
  33021. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33022. }
  33023. this._unIndexed = true;
  33024. this.synchronizeInstances();
  33025. return this;
  33026. };
  33027. /**
  33028. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33029. * This method returns the Mesh.
  33030. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33031. */
  33032. Mesh.prototype.flipFaces = function (flipNormals) {
  33033. if (flipNormals === void 0) { flipNormals = false; }
  33034. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33035. var i;
  33036. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33037. for (i = 0; i < vertex_data.normals.length; i++) {
  33038. vertex_data.normals[i] *= -1;
  33039. }
  33040. }
  33041. if (vertex_data.indices) {
  33042. var temp;
  33043. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33044. // reassign indices
  33045. temp = vertex_data.indices[i + 1];
  33046. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33047. vertex_data.indices[i + 2] = temp;
  33048. }
  33049. }
  33050. vertex_data.applyToMesh(this);
  33051. return this;
  33052. };
  33053. // Instances
  33054. /**
  33055. * Creates a new InstancedMesh object from the mesh model.
  33056. * An instance shares the same properties and the same material than its model.
  33057. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  33058. * Only these properties of each instance can then be set individually :
  33059. * - position
  33060. * - rotation
  33061. * - rotationQuaternion
  33062. * - setPivotMatrix
  33063. * - scaling
  33064. *
  33065. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33066. * Warning : this method is not supported for Line mesh and LineSystem
  33067. */
  33068. Mesh.prototype.createInstance = function (name) {
  33069. return new BABYLON.InstancedMesh(name, this);
  33070. };
  33071. /**
  33072. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33073. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33074. * This method returns the Mesh.
  33075. */
  33076. Mesh.prototype.synchronizeInstances = function () {
  33077. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33078. var instance = this.instances[instanceIndex];
  33079. instance._syncSubMeshes();
  33080. }
  33081. return this;
  33082. };
  33083. /**
  33084. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33085. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33086. * This should be used together with the simplification to avoid disappearing triangles.
  33087. * Returns the Mesh.
  33088. * @param successCallback an optional success callback to be called after the optimization finished.
  33089. */
  33090. Mesh.prototype.optimizeIndices = function (successCallback) {
  33091. var _this = this;
  33092. var indices = this.getIndices();
  33093. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33094. if (!positions || !indices) {
  33095. return this;
  33096. }
  33097. var vectorPositions = new Array();
  33098. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33099. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33100. }
  33101. var dupes = new Array();
  33102. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33103. var realPos = vectorPositions.length - 1 - iteration;
  33104. var testedPosition = vectorPositions[realPos];
  33105. for (var j = 0; j < realPos; ++j) {
  33106. var againstPosition = vectorPositions[j];
  33107. if (testedPosition.equals(againstPosition)) {
  33108. dupes[realPos] = j;
  33109. break;
  33110. }
  33111. }
  33112. }, function () {
  33113. for (var i = 0; i < indices.length; ++i) {
  33114. indices[i] = dupes[indices[i]] || indices[i];
  33115. }
  33116. //indices are now reordered
  33117. var originalSubMeshes = _this.subMeshes.slice(0);
  33118. _this.setIndices(indices);
  33119. _this.subMeshes = originalSubMeshes;
  33120. if (successCallback) {
  33121. successCallback(_this);
  33122. }
  33123. });
  33124. return this;
  33125. };
  33126. Mesh.prototype.serialize = function (serializationObject) {
  33127. serializationObject.name = this.name;
  33128. serializationObject.id = this.id;
  33129. serializationObject.type = this.getClassName();
  33130. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33131. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33132. }
  33133. serializationObject.position = this.position.asArray();
  33134. if (this.rotationQuaternion) {
  33135. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33136. }
  33137. else if (this.rotation) {
  33138. serializationObject.rotation = this.rotation.asArray();
  33139. }
  33140. serializationObject.scaling = this.scaling.asArray();
  33141. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33142. serializationObject.isEnabled = this.isEnabled(false);
  33143. serializationObject.isVisible = this.isVisible;
  33144. serializationObject.infiniteDistance = this.infiniteDistance;
  33145. serializationObject.pickable = this.isPickable;
  33146. serializationObject.receiveShadows = this.receiveShadows;
  33147. serializationObject.billboardMode = this.billboardMode;
  33148. serializationObject.visibility = this.visibility;
  33149. serializationObject.checkCollisions = this.checkCollisions;
  33150. serializationObject.isBlocker = this.isBlocker;
  33151. // Parent
  33152. if (this.parent) {
  33153. serializationObject.parentId = this.parent.id;
  33154. }
  33155. // Geometry
  33156. serializationObject.isUnIndexed = this.isUnIndexed;
  33157. var geometry = this._geometry;
  33158. if (geometry) {
  33159. var geometryId = geometry.id;
  33160. serializationObject.geometryId = geometryId;
  33161. // SubMeshes
  33162. serializationObject.subMeshes = [];
  33163. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33164. var subMesh = this.subMeshes[subIndex];
  33165. serializationObject.subMeshes.push({
  33166. materialIndex: subMesh.materialIndex,
  33167. verticesStart: subMesh.verticesStart,
  33168. verticesCount: subMesh.verticesCount,
  33169. indexStart: subMesh.indexStart,
  33170. indexCount: subMesh.indexCount
  33171. });
  33172. }
  33173. }
  33174. // Material
  33175. if (this.material) {
  33176. serializationObject.materialId = this.material.id;
  33177. }
  33178. else {
  33179. this.material = null;
  33180. }
  33181. // Morph targets
  33182. if (this.morphTargetManager) {
  33183. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33184. }
  33185. // Skeleton
  33186. if (this.skeleton) {
  33187. serializationObject.skeletonId = this.skeleton.id;
  33188. }
  33189. // Physics
  33190. //TODO implement correct serialization for physics impostors.
  33191. var impostor = this.getPhysicsImpostor();
  33192. if (impostor) {
  33193. serializationObject.physicsMass = impostor.getParam("mass");
  33194. serializationObject.physicsFriction = impostor.getParam("friction");
  33195. serializationObject.physicsRestitution = impostor.getParam("mass");
  33196. serializationObject.physicsImpostor = impostor.type;
  33197. }
  33198. // Metadata
  33199. if (this.metadata) {
  33200. serializationObject.metadata = this.metadata;
  33201. }
  33202. // Instances
  33203. serializationObject.instances = [];
  33204. for (var index = 0; index < this.instances.length; index++) {
  33205. var instance = this.instances[index];
  33206. var serializationInstance = {
  33207. name: instance.name,
  33208. id: instance.id,
  33209. position: instance.position.asArray(),
  33210. scaling: instance.scaling.asArray()
  33211. };
  33212. if (instance.parent) {
  33213. serializationInstance.parentId = instance.parent.id;
  33214. }
  33215. if (instance.rotationQuaternion) {
  33216. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33217. }
  33218. else if (instance.rotation) {
  33219. serializationInstance.rotation = instance.rotation.asArray();
  33220. }
  33221. serializationObject.instances.push(serializationInstance);
  33222. // Animations
  33223. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33224. serializationInstance.ranges = instance.serializeAnimationRanges();
  33225. }
  33226. //
  33227. // Animations
  33228. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33229. serializationObject.ranges = this.serializeAnimationRanges();
  33230. // Layer mask
  33231. serializationObject.layerMask = this.layerMask;
  33232. // Alpha
  33233. serializationObject.alphaIndex = this.alphaIndex;
  33234. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33235. // Overlay
  33236. serializationObject.overlayAlpha = this.overlayAlpha;
  33237. serializationObject.overlayColor = this.overlayColor.asArray();
  33238. serializationObject.renderOverlay = this.renderOverlay;
  33239. // Fog
  33240. serializationObject.applyFog = this.applyFog;
  33241. // Action Manager
  33242. if (this.actionManager) {
  33243. serializationObject.actions = this.actionManager.serialize(this.name);
  33244. }
  33245. };
  33246. /** @hidden */
  33247. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33248. if (!this.geometry) {
  33249. return;
  33250. }
  33251. this._markSubMeshesAsAttributesDirty();
  33252. var morphTargetManager = this._morphTargetManager;
  33253. if (morphTargetManager && morphTargetManager.vertexCount) {
  33254. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33255. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33256. this.morphTargetManager = null;
  33257. return;
  33258. }
  33259. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33260. var morphTarget = morphTargetManager.getActiveTarget(index);
  33261. var positions = morphTarget.getPositions();
  33262. if (!positions) {
  33263. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33264. return;
  33265. }
  33266. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33267. var normals = morphTarget.getNormals();
  33268. if (normals) {
  33269. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33270. }
  33271. var tangents = morphTarget.getTangents();
  33272. if (tangents) {
  33273. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33274. }
  33275. }
  33276. }
  33277. else {
  33278. var index = 0;
  33279. // Positions
  33280. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33281. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33282. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33283. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33284. }
  33285. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33286. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33287. }
  33288. index++;
  33289. }
  33290. }
  33291. };
  33292. // Statics
  33293. /**
  33294. * Returns a new Mesh object parsed from the source provided.
  33295. * The parameter `parsedMesh` is the source.
  33296. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33297. */
  33298. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33299. var mesh;
  33300. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33301. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33302. }
  33303. else {
  33304. mesh = new Mesh(parsedMesh.name, scene);
  33305. }
  33306. mesh.id = parsedMesh.id;
  33307. if (BABYLON.Tags) {
  33308. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33309. }
  33310. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33311. if (parsedMesh.metadata !== undefined) {
  33312. mesh.metadata = parsedMesh.metadata;
  33313. }
  33314. if (parsedMesh.rotationQuaternion) {
  33315. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33316. }
  33317. else if (parsedMesh.rotation) {
  33318. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33319. }
  33320. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33321. if (parsedMesh.localMatrix) {
  33322. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33323. }
  33324. else if (parsedMesh.pivotMatrix) {
  33325. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33326. }
  33327. mesh.setEnabled(parsedMesh.isEnabled);
  33328. mesh.isVisible = parsedMesh.isVisible;
  33329. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33330. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33331. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33332. if (parsedMesh.applyFog !== undefined) {
  33333. mesh.applyFog = parsedMesh.applyFog;
  33334. }
  33335. if (parsedMesh.pickable !== undefined) {
  33336. mesh.isPickable = parsedMesh.pickable;
  33337. }
  33338. if (parsedMesh.alphaIndex !== undefined) {
  33339. mesh.alphaIndex = parsedMesh.alphaIndex;
  33340. }
  33341. mesh.receiveShadows = parsedMesh.receiveShadows;
  33342. mesh.billboardMode = parsedMesh.billboardMode;
  33343. if (parsedMesh.visibility !== undefined) {
  33344. mesh.visibility = parsedMesh.visibility;
  33345. }
  33346. mesh.checkCollisions = parsedMesh.checkCollisions;
  33347. if (parsedMesh.isBlocker !== undefined) {
  33348. mesh.isBlocker = parsedMesh.isBlocker;
  33349. }
  33350. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33351. // freezeWorldMatrix
  33352. if (parsedMesh.freezeWorldMatrix) {
  33353. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33354. }
  33355. // Parent
  33356. if (parsedMesh.parentId) {
  33357. mesh._waitingParentId = parsedMesh.parentId;
  33358. }
  33359. // Actions
  33360. if (parsedMesh.actions !== undefined) {
  33361. mesh._waitingActions = parsedMesh.actions;
  33362. }
  33363. // Overlay
  33364. if (parsedMesh.overlayAlpha !== undefined) {
  33365. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33366. }
  33367. if (parsedMesh.overlayColor !== undefined) {
  33368. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33369. }
  33370. if (parsedMesh.renderOverlay !== undefined) {
  33371. mesh.renderOverlay = parsedMesh.renderOverlay;
  33372. }
  33373. // Geometry
  33374. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33375. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33376. if (parsedMesh.delayLoadingFile) {
  33377. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33378. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33379. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33380. if (parsedMesh._binaryInfo) {
  33381. mesh._binaryInfo = parsedMesh._binaryInfo;
  33382. }
  33383. mesh._delayInfo = [];
  33384. if (parsedMesh.hasUVs) {
  33385. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33386. }
  33387. if (parsedMesh.hasUVs2) {
  33388. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33389. }
  33390. if (parsedMesh.hasUVs3) {
  33391. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33392. }
  33393. if (parsedMesh.hasUVs4) {
  33394. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33395. }
  33396. if (parsedMesh.hasUVs5) {
  33397. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33398. }
  33399. if (parsedMesh.hasUVs6) {
  33400. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33401. }
  33402. if (parsedMesh.hasColors) {
  33403. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33404. }
  33405. if (parsedMesh.hasMatricesIndices) {
  33406. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33407. }
  33408. if (parsedMesh.hasMatricesWeights) {
  33409. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33410. }
  33411. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33412. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33413. mesh._checkDelayState();
  33414. }
  33415. }
  33416. else {
  33417. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33418. }
  33419. // Material
  33420. if (parsedMesh.materialId) {
  33421. mesh.setMaterialByID(parsedMesh.materialId);
  33422. }
  33423. else {
  33424. mesh.material = null;
  33425. }
  33426. // Morph targets
  33427. if (parsedMesh.morphTargetManagerId > -1) {
  33428. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33429. }
  33430. // Skeleton
  33431. if (parsedMesh.skeletonId > -1) {
  33432. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33433. if (parsedMesh.numBoneInfluencers) {
  33434. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33435. }
  33436. }
  33437. // Animations
  33438. if (parsedMesh.animations) {
  33439. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33440. var parsedAnimation = parsedMesh.animations[animationIndex];
  33441. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33442. }
  33443. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33444. }
  33445. if (parsedMesh.autoAnimate) {
  33446. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33447. }
  33448. // Layer Mask
  33449. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33450. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33451. }
  33452. else {
  33453. mesh.layerMask = 0x0FFFFFFF;
  33454. }
  33455. // Physics
  33456. if (parsedMesh.physicsImpostor) {
  33457. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33458. mass: parsedMesh.physicsMass,
  33459. friction: parsedMesh.physicsFriction,
  33460. restitution: parsedMesh.physicsRestitution
  33461. }, scene);
  33462. }
  33463. // Instances
  33464. if (parsedMesh.instances) {
  33465. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33466. var parsedInstance = parsedMesh.instances[index];
  33467. var instance = mesh.createInstance(parsedInstance.name);
  33468. if (parsedInstance.id) {
  33469. instance.id = parsedInstance.id;
  33470. }
  33471. if (BABYLON.Tags) {
  33472. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33473. }
  33474. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33475. if (parsedInstance.parentId) {
  33476. instance._waitingParentId = parsedInstance.parentId;
  33477. }
  33478. if (parsedInstance.rotationQuaternion) {
  33479. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33480. }
  33481. else if (parsedInstance.rotation) {
  33482. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33483. }
  33484. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33485. instance.checkCollisions = mesh.checkCollisions;
  33486. if (parsedMesh.animations) {
  33487. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33488. parsedAnimation = parsedMesh.animations[animationIndex];
  33489. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33490. }
  33491. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33492. if (parsedMesh.autoAnimate) {
  33493. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33494. }
  33495. }
  33496. }
  33497. }
  33498. return mesh;
  33499. };
  33500. /**
  33501. * Creates a ribbon mesh.
  33502. * Please consider using the same method from the MeshBuilder class instead.
  33503. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33504. *
  33505. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33506. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33507. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33508. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33509. * 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.
  33510. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33511. * 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
  33512. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33513. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33514. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33515. */
  33516. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33517. if (closeArray === void 0) { closeArray = false; }
  33518. if (updatable === void 0) { updatable = false; }
  33519. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33520. pathArray: pathArray,
  33521. closeArray: closeArray,
  33522. closePath: closePath,
  33523. offset: offset,
  33524. updatable: updatable,
  33525. sideOrientation: sideOrientation,
  33526. instance: instance
  33527. }, scene);
  33528. };
  33529. /**
  33530. * Creates a plane polygonal mesh. By default, this is a disc.
  33531. * Please consider using the same method from the MeshBuilder class instead.
  33532. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33533. * 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.
  33534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33535. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33537. */
  33538. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33539. if (scene === void 0) { scene = null; }
  33540. var options = {
  33541. radius: radius,
  33542. tessellation: tessellation,
  33543. sideOrientation: sideOrientation,
  33544. updatable: updatable
  33545. };
  33546. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33547. };
  33548. /**
  33549. * Creates a box mesh.
  33550. * Please consider using the same method from the MeshBuilder class instead.
  33551. * The parameter `size` sets the size (float) of each box side (default 1).
  33552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33553. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33555. */
  33556. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33557. if (scene === void 0) { scene = null; }
  33558. var options = {
  33559. size: size,
  33560. sideOrientation: sideOrientation,
  33561. updatable: updatable
  33562. };
  33563. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33564. };
  33565. /**
  33566. * Creates a sphere mesh.
  33567. * Please consider using the same method from the MeshBuilder class instead.
  33568. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33569. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33570. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33571. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33573. */
  33574. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33575. var options = {
  33576. segments: segments,
  33577. diameterX: diameter,
  33578. diameterY: diameter,
  33579. diameterZ: diameter,
  33580. sideOrientation: sideOrientation,
  33581. updatable: updatable
  33582. };
  33583. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33584. };
  33585. /**
  33586. * Creates a cylinder or a cone mesh.
  33587. * Please consider using the same method from the MeshBuilder class instead.
  33588. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33589. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33590. * 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.
  33591. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33592. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33594. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33596. */
  33597. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33598. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33599. if (scene !== undefined) {
  33600. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33601. updatable = scene;
  33602. }
  33603. scene = subdivisions;
  33604. subdivisions = 1;
  33605. }
  33606. var options = {
  33607. height: height,
  33608. diameterTop: diameterTop,
  33609. diameterBottom: diameterBottom,
  33610. tessellation: tessellation,
  33611. subdivisions: subdivisions,
  33612. sideOrientation: sideOrientation,
  33613. updatable: updatable
  33614. };
  33615. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33616. };
  33617. // Torus (Code from SharpDX.org)
  33618. /**
  33619. * Creates a torus mesh.
  33620. * Please consider using the same method from the MeshBuilder class instead.
  33621. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33622. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33623. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33625. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33627. */
  33628. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33629. var options = {
  33630. diameter: diameter,
  33631. thickness: thickness,
  33632. tessellation: tessellation,
  33633. sideOrientation: sideOrientation,
  33634. updatable: updatable
  33635. };
  33636. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33637. };
  33638. /**
  33639. * Creates a torus knot mesh.
  33640. * Please consider using the same method from the MeshBuilder class instead.
  33641. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33642. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33643. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33644. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33645. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33646. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33648. */
  33649. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33650. var options = {
  33651. radius: radius,
  33652. tube: tube,
  33653. radialSegments: radialSegments,
  33654. tubularSegments: tubularSegments,
  33655. p: p,
  33656. q: q,
  33657. sideOrientation: sideOrientation,
  33658. updatable: updatable
  33659. };
  33660. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33661. };
  33662. /**
  33663. * Creates a line mesh.
  33664. * Please consider using the same method from the MeshBuilder class instead.
  33665. * 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.
  33666. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33667. * The parameter `points` is an array successive Vector3.
  33668. * 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
  33669. * When updating an instance, remember that only point positions can change, not the number of points.
  33670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33671. */
  33672. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33673. if (scene === void 0) { scene = null; }
  33674. if (updatable === void 0) { updatable = false; }
  33675. if (instance === void 0) { instance = null; }
  33676. var options = {
  33677. points: points,
  33678. updatable: updatable,
  33679. instance: instance
  33680. };
  33681. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33682. };
  33683. /**
  33684. * Creates a dashed line mesh.
  33685. * Please consider using the same method from the MeshBuilder class instead.
  33686. * 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.
  33687. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33688. * The parameter `points` is an array successive Vector3.
  33689. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33690. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33691. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33692. * 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
  33693. * When updating an instance, remember that only point positions can change, not the number of points.
  33694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33695. */
  33696. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33697. if (scene === void 0) { scene = null; }
  33698. var options = {
  33699. points: points,
  33700. dashSize: dashSize,
  33701. gapSize: gapSize,
  33702. dashNb: dashNb,
  33703. updatable: updatable,
  33704. instance: instance
  33705. };
  33706. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33707. };
  33708. /**
  33709. * Creates a polygon mesh.
  33710. * Please consider using the same method from the MeshBuilder class instead.
  33711. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33712. * 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.
  33713. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33715. * Remember you can only change the shape positions, not their number when updating a polygon.
  33716. */
  33717. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33718. var options = {
  33719. shape: shape,
  33720. holes: holes,
  33721. updatable: updatable,
  33722. sideOrientation: sideOrientation
  33723. };
  33724. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33725. };
  33726. /**
  33727. * Creates an extruded polygon mesh, with depth in the Y direction.
  33728. * Please consider using the same method from the MeshBuilder class instead.
  33729. */
  33730. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33731. var options = {
  33732. shape: shape,
  33733. holes: holes,
  33734. depth: depth,
  33735. updatable: updatable,
  33736. sideOrientation: sideOrientation
  33737. };
  33738. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33739. };
  33740. /**
  33741. * Creates an extruded shape mesh.
  33742. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33743. * Please consider using the same method from the MeshBuilder class instead.
  33744. *
  33745. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33746. * 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
  33747. * extruded along the Z axis.
  33748. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33749. * 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.
  33750. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33751. * 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
  33752. * 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
  33753. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33755. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33757. */
  33758. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33759. if (scene === void 0) { scene = null; }
  33760. var options = {
  33761. shape: shape,
  33762. path: path,
  33763. scale: scale,
  33764. rotation: rotation,
  33765. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33766. sideOrientation: sideOrientation,
  33767. instance: instance,
  33768. updatable: updatable
  33769. };
  33770. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33771. };
  33772. /**
  33773. * Creates an custom extruded shape mesh.
  33774. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33775. * Please consider using the same method from the MeshBuilder class instead.
  33776. *
  33777. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33778. * 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
  33779. * extruded along the Z axis.
  33780. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33781. * 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
  33782. * and the distance of this point from the begining of the path :
  33783. * ```javascript
  33784. * var rotationFunction = function(i, distance) {
  33785. * // do things
  33786. * return rotationValue; }
  33787. * ```
  33788. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33789. * 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
  33790. * and the distance of this point from the begining of the path :
  33791. * ```javascript
  33792. * var scaleFunction = function(i, distance) {
  33793. * // do things
  33794. * return scaleValue;}
  33795. * ```
  33796. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33797. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33798. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33799. * 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
  33800. * 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
  33801. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33802. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33803. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33805. */
  33806. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33807. var options = {
  33808. shape: shape,
  33809. path: path,
  33810. scaleFunction: scaleFunction,
  33811. rotationFunction: rotationFunction,
  33812. ribbonCloseArray: ribbonCloseArray,
  33813. ribbonClosePath: ribbonClosePath,
  33814. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33815. sideOrientation: sideOrientation,
  33816. instance: instance,
  33817. updatable: updatable
  33818. };
  33819. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33820. };
  33821. /**
  33822. * Creates lathe mesh.
  33823. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33824. * Please consider using the same method from the MeshBuilder class instead.
  33825. * 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
  33826. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33827. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33828. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33830. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33832. */
  33833. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33834. var options = {
  33835. shape: shape,
  33836. radius: radius,
  33837. tessellation: tessellation,
  33838. sideOrientation: sideOrientation,
  33839. updatable: updatable
  33840. };
  33841. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33842. };
  33843. /**
  33844. * Creates a plane mesh.
  33845. * Please consider using the same method from the MeshBuilder class instead.
  33846. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33847. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33848. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33850. */
  33851. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33852. var options = {
  33853. size: size,
  33854. width: size,
  33855. height: size,
  33856. sideOrientation: sideOrientation,
  33857. updatable: updatable
  33858. };
  33859. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33860. };
  33861. /**
  33862. * Creates a ground mesh.
  33863. * Please consider using the same method from the MeshBuilder class instead.
  33864. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33865. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33867. */
  33868. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33869. var options = {
  33870. width: width,
  33871. height: height,
  33872. subdivisions: subdivisions,
  33873. updatable: updatable
  33874. };
  33875. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33876. };
  33877. /**
  33878. * Creates a tiled ground mesh.
  33879. * Please consider using the same method from the MeshBuilder class instead.
  33880. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33881. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33882. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33883. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33884. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33885. * numbers of subdivisions on the ground width and height of each tile.
  33886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33887. */
  33888. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33889. var options = {
  33890. xmin: xmin,
  33891. zmin: zmin,
  33892. xmax: xmax,
  33893. zmax: zmax,
  33894. subdivisions: subdivisions,
  33895. precision: precision,
  33896. updatable: updatable
  33897. };
  33898. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33899. };
  33900. /**
  33901. * Creates a ground mesh from a height map.
  33902. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33903. * Please consider using the same method from the MeshBuilder class instead.
  33904. * The parameter `url` sets the URL of the height map image resource.
  33905. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33906. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33907. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33908. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33909. * 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).
  33910. * This function is passed the newly built mesh :
  33911. * ```javascript
  33912. * function(mesh) { // do things
  33913. * return; }
  33914. * ```
  33915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33916. */
  33917. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33918. var options = {
  33919. width: width,
  33920. height: height,
  33921. subdivisions: subdivisions,
  33922. minHeight: minHeight,
  33923. maxHeight: maxHeight,
  33924. updatable: updatable,
  33925. onReady: onReady
  33926. };
  33927. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33928. };
  33929. /**
  33930. * Creates a tube mesh.
  33931. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33932. * Please consider using the same method from the MeshBuilder class instead.
  33933. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33934. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33935. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33936. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33937. * 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.
  33938. * It must return a radius value (positive float) :
  33939. * ```javascript
  33940. * var radiusFunction = function(i, distance) {
  33941. * // do things
  33942. * return radius; }
  33943. * ```
  33944. * 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
  33945. * 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
  33946. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33947. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33949. */
  33950. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33951. var options = {
  33952. path: path,
  33953. radius: radius,
  33954. tessellation: tessellation,
  33955. radiusFunction: radiusFunction,
  33956. arc: 1,
  33957. cap: cap,
  33958. updatable: updatable,
  33959. sideOrientation: sideOrientation,
  33960. instance: instance
  33961. };
  33962. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33963. };
  33964. /**
  33965. * Creates a polyhedron mesh.
  33966. * Please consider using the same method from the MeshBuilder class instead.
  33967. * 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
  33968. * to choose the wanted type.
  33969. * The parameter `size` (positive float, default 1) sets the polygon size.
  33970. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33971. * 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`.
  33972. * 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
  33973. * 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)`).
  33974. * 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
  33975. * 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.
  33976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33977. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33979. */
  33980. Mesh.CreatePolyhedron = function (name, options, scene) {
  33981. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33982. };
  33983. /**
  33984. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33985. * Please consider using the same method from the MeshBuilder class instead.
  33986. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33987. * 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`).
  33988. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33989. * 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.
  33990. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33991. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33993. */
  33994. Mesh.CreateIcoSphere = function (name, options, scene) {
  33995. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33996. };
  33997. /**
  33998. * Creates a decal mesh.
  33999. * Please consider using the same method from the MeshBuilder class instead.
  34000. * 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.
  34001. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34002. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34003. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34004. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34005. */
  34006. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34007. var options = {
  34008. position: position,
  34009. normal: normal,
  34010. size: size,
  34011. angle: angle
  34012. };
  34013. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34014. };
  34015. // Skeletons
  34016. /**
  34017. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34018. */
  34019. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34020. if (!this._sourcePositions) {
  34021. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34022. if (!source) {
  34023. return this._sourcePositions;
  34024. }
  34025. this._sourcePositions = new Float32Array(source);
  34026. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34027. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34028. }
  34029. }
  34030. return this._sourcePositions;
  34031. };
  34032. /**
  34033. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34034. */
  34035. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34036. if (!this._sourceNormals) {
  34037. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34038. if (!source) {
  34039. return this._sourceNormals;
  34040. }
  34041. this._sourceNormals = new Float32Array(source);
  34042. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34043. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34044. }
  34045. }
  34046. return this._sourceNormals;
  34047. };
  34048. /**
  34049. * Updates the vertex buffer by applying transformation from the bones.
  34050. * Returns the Mesh.
  34051. *
  34052. * @param {skeleton} skeleton to apply
  34053. */
  34054. Mesh.prototype.applySkeleton = function (skeleton) {
  34055. if (!this.geometry) {
  34056. return this;
  34057. }
  34058. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34059. return this;
  34060. }
  34061. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34062. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34063. return this;
  34064. }
  34065. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34066. return this;
  34067. }
  34068. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34069. return this;
  34070. }
  34071. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34072. return this;
  34073. }
  34074. if (!this._sourcePositions) {
  34075. var submeshes = this.subMeshes.slice();
  34076. this.setPositionsForCPUSkinning();
  34077. this.subMeshes = submeshes;
  34078. }
  34079. if (!this._sourceNormals) {
  34080. this.setNormalsForCPUSkinning();
  34081. }
  34082. // positionsData checks for not being Float32Array will only pass at most once
  34083. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34084. if (!positionsData) {
  34085. return this;
  34086. }
  34087. if (!(positionsData instanceof Float32Array)) {
  34088. positionsData = new Float32Array(positionsData);
  34089. }
  34090. // normalsData checks for not being Float32Array will only pass at most once
  34091. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34092. if (!normalsData) {
  34093. return this;
  34094. }
  34095. if (!(normalsData instanceof Float32Array)) {
  34096. normalsData = new Float32Array(normalsData);
  34097. }
  34098. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34099. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34100. if (!matricesWeightsData || !matricesIndicesData) {
  34101. return this;
  34102. }
  34103. var needExtras = this.numBoneInfluencers > 4;
  34104. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34105. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34106. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34107. var tempVector3 = BABYLON.Vector3.Zero();
  34108. var finalMatrix = new BABYLON.Matrix();
  34109. var tempMatrix = new BABYLON.Matrix();
  34110. var matWeightIdx = 0;
  34111. var inf;
  34112. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34113. var weight;
  34114. for (inf = 0; inf < 4; inf++) {
  34115. weight = matricesWeightsData[matWeightIdx + inf];
  34116. if (weight > 0) {
  34117. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34118. finalMatrix.addToSelf(tempMatrix);
  34119. }
  34120. }
  34121. if (needExtras) {
  34122. for (inf = 0; inf < 4; inf++) {
  34123. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34124. if (weight > 0) {
  34125. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34126. finalMatrix.addToSelf(tempMatrix);
  34127. }
  34128. }
  34129. }
  34130. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34131. tempVector3.toArray(positionsData, index);
  34132. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34133. tempVector3.toArray(normalsData, index);
  34134. finalMatrix.reset();
  34135. }
  34136. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34137. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34138. return this;
  34139. };
  34140. // Tools
  34141. /**
  34142. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34143. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34144. */
  34145. Mesh.MinMax = function (meshes) {
  34146. var minVector = null;
  34147. var maxVector = null;
  34148. meshes.forEach(function (mesh, index, array) {
  34149. var boundingInfo = mesh.getBoundingInfo();
  34150. var boundingBox = boundingInfo.boundingBox;
  34151. if (!minVector || !maxVector) {
  34152. minVector = boundingBox.minimumWorld;
  34153. maxVector = boundingBox.maximumWorld;
  34154. }
  34155. else {
  34156. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34157. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34158. }
  34159. });
  34160. if (!minVector || !maxVector) {
  34161. return {
  34162. min: BABYLON.Vector3.Zero(),
  34163. max: BABYLON.Vector3.Zero()
  34164. };
  34165. }
  34166. return {
  34167. min: minVector,
  34168. max: maxVector
  34169. };
  34170. };
  34171. /**
  34172. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34173. */
  34174. Mesh.Center = function (meshesOrMinMaxVector) {
  34175. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34176. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34177. };
  34178. /**
  34179. * Merge the array of meshes into a single mesh for performance reasons.
  34180. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34181. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34182. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34183. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34184. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34185. */
  34186. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34187. if (disposeSource === void 0) { disposeSource = true; }
  34188. var index;
  34189. if (!allow32BitsIndices) {
  34190. var totalVertices = 0;
  34191. // Counting vertices
  34192. for (index = 0; index < meshes.length; index++) {
  34193. if (meshes[index]) {
  34194. totalVertices += meshes[index].getTotalVertices();
  34195. if (totalVertices > 65536) {
  34196. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34197. return null;
  34198. }
  34199. }
  34200. }
  34201. }
  34202. // Merge
  34203. var vertexData = null;
  34204. var otherVertexData;
  34205. var indiceArray = new Array();
  34206. var source = null;
  34207. for (index = 0; index < meshes.length; index++) {
  34208. if (meshes[index]) {
  34209. var wm = meshes[index].computeWorldMatrix(true);
  34210. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34211. otherVertexData.transform(wm);
  34212. if (vertexData) {
  34213. vertexData.merge(otherVertexData, allow32BitsIndices);
  34214. }
  34215. else {
  34216. vertexData = otherVertexData;
  34217. source = meshes[index];
  34218. }
  34219. if (subdivideWithSubMeshes) {
  34220. indiceArray.push(meshes[index].getTotalIndices());
  34221. }
  34222. }
  34223. }
  34224. source = source;
  34225. if (!meshSubclass) {
  34226. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34227. }
  34228. vertexData.applyToMesh(meshSubclass);
  34229. // Setting properties
  34230. meshSubclass.material = source.material;
  34231. meshSubclass.checkCollisions = source.checkCollisions;
  34232. // Cleaning
  34233. if (disposeSource) {
  34234. for (index = 0; index < meshes.length; index++) {
  34235. if (meshes[index]) {
  34236. meshes[index].dispose();
  34237. }
  34238. }
  34239. }
  34240. // Subdivide
  34241. if (subdivideWithSubMeshes) {
  34242. //-- removal of global submesh
  34243. meshSubclass.releaseSubMeshes();
  34244. index = 0;
  34245. var offset = 0;
  34246. //-- apply subdivision according to index table
  34247. while (index < indiceArray.length) {
  34248. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34249. offset += indiceArray[index];
  34250. index++;
  34251. }
  34252. }
  34253. return meshSubclass;
  34254. };
  34255. // Consts
  34256. Mesh._FRONTSIDE = 0;
  34257. Mesh._BACKSIDE = 1;
  34258. Mesh._DOUBLESIDE = 2;
  34259. Mesh._DEFAULTSIDE = 0;
  34260. Mesh._NO_CAP = 0;
  34261. Mesh._CAP_START = 1;
  34262. Mesh._CAP_END = 2;
  34263. Mesh._CAP_ALL = 3;
  34264. return Mesh;
  34265. }(BABYLON.AbstractMesh));
  34266. BABYLON.Mesh = Mesh;
  34267. })(BABYLON || (BABYLON = {}));
  34268. //# sourceMappingURL=babylon.mesh.js.map
  34269. var BABYLON;
  34270. (function (BABYLON) {
  34271. var BaseSubMesh = /** @class */ (function () {
  34272. function BaseSubMesh() {
  34273. }
  34274. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34275. get: function () {
  34276. return this._materialEffect;
  34277. },
  34278. enumerable: true,
  34279. configurable: true
  34280. });
  34281. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34282. if (defines === void 0) { defines = null; }
  34283. if (this._materialEffect === effect) {
  34284. if (!effect) {
  34285. this._materialDefines = null;
  34286. }
  34287. return;
  34288. }
  34289. this._materialDefines = defines;
  34290. this._materialEffect = effect;
  34291. };
  34292. return BaseSubMesh;
  34293. }());
  34294. BABYLON.BaseSubMesh = BaseSubMesh;
  34295. var SubMesh = /** @class */ (function (_super) {
  34296. __extends(SubMesh, _super);
  34297. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34298. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34299. var _this = _super.call(this) || this;
  34300. _this.materialIndex = materialIndex;
  34301. _this.verticesStart = verticesStart;
  34302. _this.verticesCount = verticesCount;
  34303. _this.indexStart = indexStart;
  34304. _this.indexCount = indexCount;
  34305. /** @hidden */
  34306. _this._renderId = 0;
  34307. _this._mesh = mesh;
  34308. _this._renderingMesh = renderingMesh || mesh;
  34309. mesh.subMeshes.push(_this);
  34310. _this._trianglePlanes = [];
  34311. _this._id = mesh.subMeshes.length - 1;
  34312. if (createBoundingBox) {
  34313. _this.refreshBoundingInfo();
  34314. mesh.computeWorldMatrix(true);
  34315. }
  34316. return _this;
  34317. }
  34318. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34319. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34320. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34321. };
  34322. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34323. get: function () {
  34324. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34325. },
  34326. enumerable: true,
  34327. configurable: true
  34328. });
  34329. /**
  34330. * Returns the submesh BoudingInfo object.
  34331. */
  34332. SubMesh.prototype.getBoundingInfo = function () {
  34333. if (this.IsGlobal) {
  34334. return this._mesh.getBoundingInfo();
  34335. }
  34336. return this._boundingInfo;
  34337. };
  34338. /**
  34339. * Sets the submesh BoundingInfo.
  34340. * Return the SubMesh.
  34341. */
  34342. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34343. this._boundingInfo = boundingInfo;
  34344. return this;
  34345. };
  34346. /**
  34347. * Returns the mesh of the current submesh.
  34348. */
  34349. SubMesh.prototype.getMesh = function () {
  34350. return this._mesh;
  34351. };
  34352. /**
  34353. * Returns the rendering mesh of the submesh.
  34354. */
  34355. SubMesh.prototype.getRenderingMesh = function () {
  34356. return this._renderingMesh;
  34357. };
  34358. /**
  34359. * Returns the submesh material.
  34360. */
  34361. SubMesh.prototype.getMaterial = function () {
  34362. var rootMaterial = this._renderingMesh.material;
  34363. if (rootMaterial === null || rootMaterial === undefined) {
  34364. return this._mesh.getScene().defaultMaterial;
  34365. }
  34366. else if (rootMaterial.getSubMaterial) {
  34367. var multiMaterial = rootMaterial;
  34368. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34369. if (this._currentMaterial !== effectiveMaterial) {
  34370. this._currentMaterial = effectiveMaterial;
  34371. this._materialDefines = null;
  34372. }
  34373. return effectiveMaterial;
  34374. }
  34375. return rootMaterial;
  34376. };
  34377. // Methods
  34378. /**
  34379. * Sets a new updated BoundingInfo object to the submesh.
  34380. * Returns the SubMesh.
  34381. */
  34382. SubMesh.prototype.refreshBoundingInfo = function () {
  34383. this._lastColliderWorldVertices = null;
  34384. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34385. return this;
  34386. }
  34387. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34388. if (!data) {
  34389. this._boundingInfo = this._mesh.getBoundingInfo();
  34390. return this;
  34391. }
  34392. var indices = this._renderingMesh.getIndices();
  34393. var extend;
  34394. //is this the only submesh?
  34395. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34396. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34397. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34398. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34399. }
  34400. else {
  34401. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34402. }
  34403. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34404. return this;
  34405. };
  34406. /** @hidden */
  34407. SubMesh.prototype._checkCollision = function (collider) {
  34408. var boundingInfo = this.getBoundingInfo();
  34409. return boundingInfo._checkCollision(collider);
  34410. };
  34411. /**
  34412. * Updates the submesh BoundingInfo.
  34413. * Returns the Submesh.
  34414. */
  34415. SubMesh.prototype.updateBoundingInfo = function (world) {
  34416. var boundingInfo = this.getBoundingInfo();
  34417. if (!boundingInfo) {
  34418. this.refreshBoundingInfo();
  34419. boundingInfo = this.getBoundingInfo();
  34420. }
  34421. boundingInfo.update(world);
  34422. return this;
  34423. };
  34424. /**
  34425. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34426. * Boolean returned.
  34427. */
  34428. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34429. var boundingInfo = this.getBoundingInfo();
  34430. if (!boundingInfo) {
  34431. return false;
  34432. }
  34433. return boundingInfo.isInFrustum(frustumPlanes);
  34434. };
  34435. /**
  34436. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34437. * Boolean returned.
  34438. */
  34439. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34440. var boundingInfo = this.getBoundingInfo();
  34441. if (!boundingInfo) {
  34442. return false;
  34443. }
  34444. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34445. };
  34446. /**
  34447. * Renders the submesh.
  34448. * Returns it.
  34449. */
  34450. SubMesh.prototype.render = function (enableAlphaMode) {
  34451. this._renderingMesh.render(this, enableAlphaMode);
  34452. return this;
  34453. };
  34454. /**
  34455. * Returns a new Index Buffer.
  34456. * Type returned : WebGLBuffer.
  34457. */
  34458. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34459. if (!this._linesIndexBuffer) {
  34460. var linesIndices = [];
  34461. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34462. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34463. }
  34464. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34465. this.linesIndexCount = linesIndices.length;
  34466. }
  34467. return this._linesIndexBuffer;
  34468. };
  34469. /**
  34470. * True is the passed Ray intersects the submesh bounding box.
  34471. * Boolean returned.
  34472. */
  34473. SubMesh.prototype.canIntersects = function (ray) {
  34474. var boundingInfo = this.getBoundingInfo();
  34475. if (!boundingInfo) {
  34476. return false;
  34477. }
  34478. return ray.intersectsBox(boundingInfo.boundingBox);
  34479. };
  34480. /**
  34481. * Returns an object IntersectionInfo.
  34482. */
  34483. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34484. var intersectInfo = null;
  34485. var material = this.getMaterial();
  34486. if (!material) {
  34487. return null;
  34488. }
  34489. switch (material.fillMode) {
  34490. case BABYLON.Material.PointListDrawMode:
  34491. case BABYLON.Material.LineListDrawMode:
  34492. case BABYLON.Material.LineLoopDrawMode:
  34493. case BABYLON.Material.LineStripDrawMode:
  34494. case BABYLON.Material.TriangleFanDrawMode:
  34495. case BABYLON.Material.TriangleStripDrawMode:
  34496. return null;
  34497. }
  34498. // LineMesh first as it's also a Mesh...
  34499. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34500. var lineMesh = this._mesh;
  34501. // Line test
  34502. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34503. var p0 = positions[indices[index]];
  34504. var p1 = positions[indices[index + 1]];
  34505. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34506. if (length < 0) {
  34507. continue;
  34508. }
  34509. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34510. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34511. if (fastCheck) {
  34512. break;
  34513. }
  34514. }
  34515. }
  34516. }
  34517. else {
  34518. // Triangles test
  34519. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34520. var p0 = positions[indices[index]];
  34521. var p1 = positions[indices[index + 1]];
  34522. var p2 = positions[indices[index + 2]];
  34523. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34524. if (currentIntersectInfo) {
  34525. if (currentIntersectInfo.distance < 0) {
  34526. continue;
  34527. }
  34528. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34529. intersectInfo = currentIntersectInfo;
  34530. intersectInfo.faceId = index / 3;
  34531. if (fastCheck) {
  34532. break;
  34533. }
  34534. }
  34535. }
  34536. }
  34537. }
  34538. return intersectInfo;
  34539. };
  34540. /** @hidden */
  34541. SubMesh.prototype._rebuild = function () {
  34542. if (this._linesIndexBuffer) {
  34543. this._linesIndexBuffer = null;
  34544. }
  34545. };
  34546. // Clone
  34547. /**
  34548. * Creates a new Submesh from the passed Mesh.
  34549. */
  34550. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34551. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34552. if (!this.IsGlobal) {
  34553. var boundingInfo = this.getBoundingInfo();
  34554. if (!boundingInfo) {
  34555. return result;
  34556. }
  34557. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34558. }
  34559. return result;
  34560. };
  34561. // Dispose
  34562. /**
  34563. * Disposes the Submesh.
  34564. * Returns nothing.
  34565. */
  34566. SubMesh.prototype.dispose = function () {
  34567. if (this._linesIndexBuffer) {
  34568. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34569. this._linesIndexBuffer = null;
  34570. }
  34571. // Remove from mesh
  34572. var index = this._mesh.subMeshes.indexOf(this);
  34573. this._mesh.subMeshes.splice(index, 1);
  34574. };
  34575. // Statics
  34576. /**
  34577. * Creates a new Submesh from the passed parameters :
  34578. * - materialIndex (integer) : the index of the main mesh material.
  34579. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34580. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34581. * - mesh (Mesh) : the main mesh to create the submesh from.
  34582. * - renderingMesh (optional Mesh) : rendering mesh.
  34583. */
  34584. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34585. var minVertexIndex = Number.MAX_VALUE;
  34586. var maxVertexIndex = -Number.MAX_VALUE;
  34587. renderingMesh = (renderingMesh || mesh);
  34588. var indices = renderingMesh.getIndices();
  34589. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34590. var vertexIndex = indices[index];
  34591. if (vertexIndex < minVertexIndex)
  34592. minVertexIndex = vertexIndex;
  34593. if (vertexIndex > maxVertexIndex)
  34594. maxVertexIndex = vertexIndex;
  34595. }
  34596. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34597. };
  34598. return SubMesh;
  34599. }(BaseSubMesh));
  34600. BABYLON.SubMesh = SubMesh;
  34601. })(BABYLON || (BABYLON = {}));
  34602. //# sourceMappingURL=babylon.subMesh.js.map
  34603. var __assign = (this && this.__assign) || function () {
  34604. __assign = Object.assign || function(t) {
  34605. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34606. s = arguments[i];
  34607. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34608. t[p] = s[p];
  34609. }
  34610. return t;
  34611. };
  34612. return __assign.apply(this, arguments);
  34613. };
  34614. var BABYLON;
  34615. (function (BABYLON) {
  34616. /**
  34617. * Manages the defines for the Material
  34618. */
  34619. var MaterialDefines = /** @class */ (function () {
  34620. function MaterialDefines() {
  34621. this._isDirty = true;
  34622. /** @hidden */
  34623. this._areLightsDirty = true;
  34624. /** @hidden */
  34625. this._areAttributesDirty = true;
  34626. /** @hidden */
  34627. this._areTexturesDirty = true;
  34628. /** @hidden */
  34629. this._areFresnelDirty = true;
  34630. /** @hidden */
  34631. this._areMiscDirty = true;
  34632. /** @hidden */
  34633. this._areImageProcessingDirty = true;
  34634. /** @hidden */
  34635. this._normals = false;
  34636. /** @hidden */
  34637. this._uvs = false;
  34638. /** @hidden */
  34639. this._needNormals = false;
  34640. /** @hidden */
  34641. this._needUVs = false;
  34642. }
  34643. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34644. /**
  34645. * Specifies if the material needs to be re-calculated
  34646. */
  34647. get: function () {
  34648. return this._isDirty;
  34649. },
  34650. enumerable: true,
  34651. configurable: true
  34652. });
  34653. /**
  34654. * Marks the material to indicate that it has been re-calculated
  34655. */
  34656. MaterialDefines.prototype.markAsProcessed = function () {
  34657. this._isDirty = false;
  34658. this._areAttributesDirty = false;
  34659. this._areTexturesDirty = false;
  34660. this._areFresnelDirty = false;
  34661. this._areLightsDirty = false;
  34662. this._areMiscDirty = false;
  34663. this._areImageProcessingDirty = false;
  34664. };
  34665. /**
  34666. * Marks the material to indicate that it needs to be re-calculated
  34667. */
  34668. MaterialDefines.prototype.markAsUnprocessed = function () {
  34669. this._isDirty = true;
  34670. };
  34671. /**
  34672. * Marks the material to indicate all of its defines need to be re-calculated
  34673. */
  34674. MaterialDefines.prototype.markAllAsDirty = function () {
  34675. this._areTexturesDirty = true;
  34676. this._areAttributesDirty = true;
  34677. this._areLightsDirty = true;
  34678. this._areFresnelDirty = true;
  34679. this._areMiscDirty = true;
  34680. this._areImageProcessingDirty = true;
  34681. this._isDirty = true;
  34682. };
  34683. /**
  34684. * Marks the material to indicate that image processing needs to be re-calculated
  34685. */
  34686. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34687. this._areImageProcessingDirty = true;
  34688. this._isDirty = true;
  34689. };
  34690. /**
  34691. * Marks the material to indicate the lights need to be re-calculated
  34692. */
  34693. MaterialDefines.prototype.markAsLightDirty = function () {
  34694. this._areLightsDirty = true;
  34695. this._isDirty = true;
  34696. };
  34697. /**
  34698. * Marks the attribute state as changed
  34699. */
  34700. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34701. this._areAttributesDirty = true;
  34702. this._isDirty = true;
  34703. };
  34704. /**
  34705. * Marks the texture state as changed
  34706. */
  34707. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34708. this._areTexturesDirty = true;
  34709. this._isDirty = true;
  34710. };
  34711. /**
  34712. * Marks the fresnel state as changed
  34713. */
  34714. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34715. this._areFresnelDirty = true;
  34716. this._isDirty = true;
  34717. };
  34718. /**
  34719. * Marks the misc state as changed
  34720. */
  34721. MaterialDefines.prototype.markAsMiscDirty = function () {
  34722. this._areMiscDirty = true;
  34723. this._isDirty = true;
  34724. };
  34725. /**
  34726. * Rebuilds the material defines
  34727. */
  34728. MaterialDefines.prototype.rebuild = function () {
  34729. if (this._keys) {
  34730. delete this._keys;
  34731. }
  34732. this._keys = [];
  34733. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34734. var key = _a[_i];
  34735. if (key[0] === "_") {
  34736. continue;
  34737. }
  34738. this._keys.push(key);
  34739. }
  34740. };
  34741. /**
  34742. * Specifies if two material defines are equal
  34743. * @param other - A material define instance to compare to
  34744. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34745. */
  34746. MaterialDefines.prototype.isEqual = function (other) {
  34747. if (this._keys.length !== other._keys.length) {
  34748. return false;
  34749. }
  34750. for (var index = 0; index < this._keys.length; index++) {
  34751. var prop = this._keys[index];
  34752. if (this[prop] !== other[prop]) {
  34753. return false;
  34754. }
  34755. }
  34756. return true;
  34757. };
  34758. /**
  34759. * Clones this instance's defines to another instance
  34760. * @param other - material defines to clone values to
  34761. */
  34762. MaterialDefines.prototype.cloneTo = function (other) {
  34763. if (this._keys.length !== other._keys.length) {
  34764. other._keys = this._keys.slice(0);
  34765. }
  34766. for (var index = 0; index < this._keys.length; index++) {
  34767. var prop = this._keys[index];
  34768. other[prop] = this[prop];
  34769. }
  34770. };
  34771. /**
  34772. * Resets the material define values
  34773. */
  34774. MaterialDefines.prototype.reset = function () {
  34775. for (var index = 0; index < this._keys.length; index++) {
  34776. var prop = this._keys[index];
  34777. var type = typeof this[prop];
  34778. switch (type) {
  34779. case "number":
  34780. this[prop] = 0;
  34781. break;
  34782. case "string":
  34783. this[prop] = "";
  34784. break;
  34785. default:
  34786. this[prop] = false;
  34787. break;
  34788. }
  34789. }
  34790. };
  34791. /**
  34792. * Converts the material define values to a string
  34793. * @returns - String of material define information
  34794. */
  34795. MaterialDefines.prototype.toString = function () {
  34796. var result = "";
  34797. for (var index = 0; index < this._keys.length; index++) {
  34798. var prop = this._keys[index];
  34799. var value = this[prop];
  34800. var type = typeof value;
  34801. switch (type) {
  34802. case "number":
  34803. case "string":
  34804. result += "#define " + prop + " " + value + "\n";
  34805. break;
  34806. default:
  34807. if (value) {
  34808. result += "#define " + prop + "\n";
  34809. }
  34810. break;
  34811. }
  34812. }
  34813. return result;
  34814. };
  34815. return MaterialDefines;
  34816. }());
  34817. BABYLON.MaterialDefines = MaterialDefines;
  34818. /**
  34819. * Base class for the main features of a material in Babylon.js
  34820. */
  34821. var Material = /** @class */ (function () {
  34822. /**
  34823. * Creates a material instance
  34824. * @param name defines the name of the material
  34825. * @param scene defines the scene to reference
  34826. * @param doNotAdd specifies if the material should be added to the scene
  34827. */
  34828. function Material(name, scene, doNotAdd) {
  34829. /**
  34830. * Specifies if the ready state should be checked on each call
  34831. */
  34832. this.checkReadyOnEveryCall = false;
  34833. /**
  34834. * Specifies if the ready state should be checked once
  34835. */
  34836. this.checkReadyOnlyOnce = false;
  34837. /**
  34838. * The state of the material
  34839. */
  34840. this.state = "";
  34841. /**
  34842. * The alpha value of the material
  34843. */
  34844. this._alpha = 1.0;
  34845. /**
  34846. * Specifies if back face culling is enabled
  34847. */
  34848. this._backFaceCulling = true;
  34849. /**
  34850. * Specifies if the material should be serialized
  34851. */
  34852. this.doNotSerialize = false;
  34853. /**
  34854. * Specifies if the effect should be stored on sub meshes
  34855. */
  34856. this.storeEffectOnSubMeshes = false;
  34857. /**
  34858. * An event triggered when the material is disposed
  34859. */
  34860. this.onDisposeObservable = new BABYLON.Observable();
  34861. /**
  34862. * Stores the value of the alpha mode
  34863. */
  34864. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34865. /**
  34866. * Stores the state of the need depth pre-pass value
  34867. */
  34868. this._needDepthPrePass = false;
  34869. /**
  34870. * Specifies if depth writing should be disabled
  34871. */
  34872. this.disableDepthWrite = false;
  34873. /**
  34874. * Specifies if depth writing should be forced
  34875. */
  34876. this.forceDepthWrite = false;
  34877. /**
  34878. * Specifies if there should be a separate pass for culling
  34879. */
  34880. this.separateCullingPass = false;
  34881. /**
  34882. * Stores the state specifing if fog should be enabled
  34883. */
  34884. this._fogEnabled = true;
  34885. /**
  34886. * Stores the size of points
  34887. */
  34888. this.pointSize = 1.0;
  34889. /**
  34890. * Stores the z offset value
  34891. */
  34892. this.zOffset = 0;
  34893. /**
  34894. * @hidden
  34895. * Specifies if the material was previously ready
  34896. */
  34897. this._wasPreviouslyReady = false;
  34898. /**
  34899. * Stores the fill mode state
  34900. */
  34901. this._fillMode = Material.TriangleFillMode;
  34902. this.name = name;
  34903. this.id = name || BABYLON.Tools.RandomId();
  34904. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34905. this.uniqueId = this._scene.getUniqueId();
  34906. if (this._scene.useRightHandedSystem) {
  34907. this.sideOrientation = Material.ClockWiseSideOrientation;
  34908. }
  34909. else {
  34910. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34911. }
  34912. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34913. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34914. if (!doNotAdd) {
  34915. this._scene.materials.push(this);
  34916. }
  34917. }
  34918. Object.defineProperty(Material, "TriangleFillMode", {
  34919. /**
  34920. * Returns the triangle fill mode
  34921. */
  34922. get: function () {
  34923. return Material._TriangleFillMode;
  34924. },
  34925. enumerable: true,
  34926. configurable: true
  34927. });
  34928. Object.defineProperty(Material, "WireFrameFillMode", {
  34929. /**
  34930. * Returns the wireframe mode
  34931. */
  34932. get: function () {
  34933. return Material._WireFrameFillMode;
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(Material, "PointFillMode", {
  34939. /**
  34940. * Returns the point fill mode
  34941. */
  34942. get: function () {
  34943. return Material._PointFillMode;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. Object.defineProperty(Material, "PointListDrawMode", {
  34949. /**
  34950. * Returns the point list draw mode
  34951. */
  34952. get: function () {
  34953. return Material._PointListDrawMode;
  34954. },
  34955. enumerable: true,
  34956. configurable: true
  34957. });
  34958. Object.defineProperty(Material, "LineListDrawMode", {
  34959. /**
  34960. * Returns the line list draw mode
  34961. */
  34962. get: function () {
  34963. return Material._LineListDrawMode;
  34964. },
  34965. enumerable: true,
  34966. configurable: true
  34967. });
  34968. Object.defineProperty(Material, "LineLoopDrawMode", {
  34969. /**
  34970. * Returns the line loop draw mode
  34971. */
  34972. get: function () {
  34973. return Material._LineLoopDrawMode;
  34974. },
  34975. enumerable: true,
  34976. configurable: true
  34977. });
  34978. Object.defineProperty(Material, "LineStripDrawMode", {
  34979. /**
  34980. * Returns the line strip draw mode
  34981. */
  34982. get: function () {
  34983. return Material._LineStripDrawMode;
  34984. },
  34985. enumerable: true,
  34986. configurable: true
  34987. });
  34988. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34989. /**
  34990. * Returns the triangle strip draw mode
  34991. */
  34992. get: function () {
  34993. return Material._TriangleStripDrawMode;
  34994. },
  34995. enumerable: true,
  34996. configurable: true
  34997. });
  34998. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34999. /**
  35000. * Returns the triangle fan draw mode
  35001. */
  35002. get: function () {
  35003. return Material._TriangleFanDrawMode;
  35004. },
  35005. enumerable: true,
  35006. configurable: true
  35007. });
  35008. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35009. /**
  35010. * Returns the clock-wise side orientation
  35011. */
  35012. get: function () {
  35013. return Material._ClockWiseSideOrientation;
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35019. /**
  35020. * Returns the counter clock-wise side orientation
  35021. */
  35022. get: function () {
  35023. return Material._CounterClockWiseSideOrientation;
  35024. },
  35025. enumerable: true,
  35026. configurable: true
  35027. });
  35028. Object.defineProperty(Material, "TextureDirtyFlag", {
  35029. /**
  35030. * Returns the dirty texture flag value
  35031. */
  35032. get: function () {
  35033. return Material._TextureDirtyFlag;
  35034. },
  35035. enumerable: true,
  35036. configurable: true
  35037. });
  35038. Object.defineProperty(Material, "LightDirtyFlag", {
  35039. /**
  35040. * Returns the dirty light flag value
  35041. */
  35042. get: function () {
  35043. return Material._LightDirtyFlag;
  35044. },
  35045. enumerable: true,
  35046. configurable: true
  35047. });
  35048. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35049. /**
  35050. * Returns the dirty fresnel flag value
  35051. */
  35052. get: function () {
  35053. return Material._FresnelDirtyFlag;
  35054. },
  35055. enumerable: true,
  35056. configurable: true
  35057. });
  35058. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35059. /**
  35060. * Returns the dirty attributes flag value
  35061. */
  35062. get: function () {
  35063. return Material._AttributesDirtyFlag;
  35064. },
  35065. enumerable: true,
  35066. configurable: true
  35067. });
  35068. Object.defineProperty(Material, "MiscDirtyFlag", {
  35069. /**
  35070. * Returns the dirty misc flag value
  35071. */
  35072. get: function () {
  35073. return Material._MiscDirtyFlag;
  35074. },
  35075. enumerable: true,
  35076. configurable: true
  35077. });
  35078. Object.defineProperty(Material.prototype, "alpha", {
  35079. /**
  35080. * Gets the alpha value of the material
  35081. */
  35082. get: function () {
  35083. return this._alpha;
  35084. },
  35085. /**
  35086. * Sets the alpha value of the material
  35087. */
  35088. set: function (value) {
  35089. if (this._alpha === value) {
  35090. return;
  35091. }
  35092. this._alpha = value;
  35093. this.markAsDirty(Material.MiscDirtyFlag);
  35094. },
  35095. enumerable: true,
  35096. configurable: true
  35097. });
  35098. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35099. /**
  35100. * Gets the back-face culling state
  35101. */
  35102. get: function () {
  35103. return this._backFaceCulling;
  35104. },
  35105. /**
  35106. * Sets the back-face culling state
  35107. */
  35108. set: function (value) {
  35109. if (this._backFaceCulling === value) {
  35110. return;
  35111. }
  35112. this._backFaceCulling = value;
  35113. this.markAsDirty(Material.TextureDirtyFlag);
  35114. },
  35115. enumerable: true,
  35116. configurable: true
  35117. });
  35118. Object.defineProperty(Material.prototype, "onDispose", {
  35119. /**
  35120. * Called during a dispose event
  35121. */
  35122. set: function (callback) {
  35123. if (this._onDisposeObserver) {
  35124. this.onDisposeObservable.remove(this._onDisposeObserver);
  35125. }
  35126. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35127. },
  35128. enumerable: true,
  35129. configurable: true
  35130. });
  35131. Object.defineProperty(Material.prototype, "onBindObservable", {
  35132. /**
  35133. * An event triggered when the material is bound
  35134. */
  35135. get: function () {
  35136. if (!this._onBindObservable) {
  35137. this._onBindObservable = new BABYLON.Observable();
  35138. }
  35139. return this._onBindObservable;
  35140. },
  35141. enumerable: true,
  35142. configurable: true
  35143. });
  35144. Object.defineProperty(Material.prototype, "onBind", {
  35145. /**
  35146. * Called during a bind event
  35147. */
  35148. set: function (callback) {
  35149. if (this._onBindObserver) {
  35150. this.onBindObservable.remove(this._onBindObserver);
  35151. }
  35152. this._onBindObserver = this.onBindObservable.add(callback);
  35153. },
  35154. enumerable: true,
  35155. configurable: true
  35156. });
  35157. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35158. /**
  35159. * An event triggered when the material is unbound
  35160. */
  35161. get: function () {
  35162. if (!this._onUnBindObservable) {
  35163. this._onUnBindObservable = new BABYLON.Observable();
  35164. }
  35165. return this._onUnBindObservable;
  35166. },
  35167. enumerable: true,
  35168. configurable: true
  35169. });
  35170. Object.defineProperty(Material.prototype, "alphaMode", {
  35171. /**
  35172. * Gets the value of the alpha mode
  35173. */
  35174. get: function () {
  35175. return this._alphaMode;
  35176. },
  35177. /**
  35178. * Sets the value of the alpha mode.
  35179. *
  35180. * | Value | Type | Description |
  35181. * | --- | --- | --- |
  35182. * | 0 | ALPHA_DISABLE | |
  35183. * | 1 | ALPHA_ADD | |
  35184. * | 2 | ALPHA_COMBINE | |
  35185. * | 3 | ALPHA_SUBTRACT | |
  35186. * | 4 | ALPHA_MULTIPLY | |
  35187. * | 5 | ALPHA_MAXIMIZED | |
  35188. * | 6 | ALPHA_ONEONE | |
  35189. * | 7 | ALPHA_PREMULTIPLIED | |
  35190. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35191. * | 9 | ALPHA_INTERPOLATE | |
  35192. * | 10 | ALPHA_SCREENMODE | |
  35193. *
  35194. */
  35195. set: function (value) {
  35196. if (this._alphaMode === value) {
  35197. return;
  35198. }
  35199. this._alphaMode = value;
  35200. this.markAsDirty(Material.TextureDirtyFlag);
  35201. },
  35202. enumerable: true,
  35203. configurable: true
  35204. });
  35205. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35206. /**
  35207. * Gets the depth pre-pass value
  35208. */
  35209. get: function () {
  35210. return this._needDepthPrePass;
  35211. },
  35212. /**
  35213. * Sets the need depth pre-pass value
  35214. */
  35215. set: function (value) {
  35216. if (this._needDepthPrePass === value) {
  35217. return;
  35218. }
  35219. this._needDepthPrePass = value;
  35220. if (this._needDepthPrePass) {
  35221. this.checkReadyOnEveryCall = true;
  35222. }
  35223. },
  35224. enumerable: true,
  35225. configurable: true
  35226. });
  35227. Object.defineProperty(Material.prototype, "fogEnabled", {
  35228. /**
  35229. * Gets the value of the fog enabled state
  35230. */
  35231. get: function () {
  35232. return this._fogEnabled;
  35233. },
  35234. /**
  35235. * Sets the state for enabling fog
  35236. */
  35237. set: function (value) {
  35238. if (this._fogEnabled === value) {
  35239. return;
  35240. }
  35241. this._fogEnabled = value;
  35242. this.markAsDirty(Material.MiscDirtyFlag);
  35243. },
  35244. enumerable: true,
  35245. configurable: true
  35246. });
  35247. Object.defineProperty(Material.prototype, "wireframe", {
  35248. /**
  35249. * Gets a value specifying if wireframe mode is enabled
  35250. */
  35251. get: function () {
  35252. switch (this._fillMode) {
  35253. case Material.WireFrameFillMode:
  35254. case Material.LineListDrawMode:
  35255. case Material.LineLoopDrawMode:
  35256. case Material.LineStripDrawMode:
  35257. return true;
  35258. }
  35259. return this._scene.forceWireframe;
  35260. },
  35261. /**
  35262. * Sets the state of wireframe mode
  35263. */
  35264. set: function (value) {
  35265. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(Material.prototype, "pointsCloud", {
  35271. /**
  35272. * Gets the value specifying if point clouds are enabled
  35273. */
  35274. get: function () {
  35275. switch (this._fillMode) {
  35276. case Material.PointFillMode:
  35277. case Material.PointListDrawMode:
  35278. return true;
  35279. }
  35280. return this._scene.forcePointsCloud;
  35281. },
  35282. /**
  35283. * Sets the state of point cloud mode
  35284. */
  35285. set: function (value) {
  35286. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35287. },
  35288. enumerable: true,
  35289. configurable: true
  35290. });
  35291. Object.defineProperty(Material.prototype, "fillMode", {
  35292. /**
  35293. * Gets the material fill mode
  35294. */
  35295. get: function () {
  35296. return this._fillMode;
  35297. },
  35298. /**
  35299. * Sets the material fill mode
  35300. */
  35301. set: function (value) {
  35302. if (this._fillMode === value) {
  35303. return;
  35304. }
  35305. this._fillMode = value;
  35306. this.markAsDirty(Material.MiscDirtyFlag);
  35307. },
  35308. enumerable: true,
  35309. configurable: true
  35310. });
  35311. /**
  35312. * Returns a string representation of the current material
  35313. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35314. * @returns a string with material information
  35315. */
  35316. Material.prototype.toString = function (fullDetails) {
  35317. var ret = "Name: " + this.name;
  35318. if (fullDetails) {
  35319. }
  35320. return ret;
  35321. };
  35322. /**
  35323. * Gets the class name of the material
  35324. * @returns a string with the class name of the material
  35325. */
  35326. Material.prototype.getClassName = function () {
  35327. return "Material";
  35328. };
  35329. Object.defineProperty(Material.prototype, "isFrozen", {
  35330. /**
  35331. * Specifies if updates for the material been locked
  35332. */
  35333. get: function () {
  35334. return this.checkReadyOnlyOnce;
  35335. },
  35336. enumerable: true,
  35337. configurable: true
  35338. });
  35339. /**
  35340. * Locks updates for the material
  35341. */
  35342. Material.prototype.freeze = function () {
  35343. this.checkReadyOnlyOnce = true;
  35344. };
  35345. /**
  35346. * Unlocks updates for the material
  35347. */
  35348. Material.prototype.unfreeze = function () {
  35349. this.checkReadyOnlyOnce = false;
  35350. };
  35351. /**
  35352. * Specifies if the material is ready to be used
  35353. * @param mesh defines the mesh to check
  35354. * @param useInstances specifies if instances should be used
  35355. * @returns a boolean indicating if the material is ready to be used
  35356. */
  35357. Material.prototype.isReady = function (mesh, useInstances) {
  35358. return true;
  35359. };
  35360. /**
  35361. * Specifies that the submesh is ready to be used
  35362. * @param mesh defines the mesh to check
  35363. * @param subMesh defines which submesh to check
  35364. * @param useInstances specifies that instances should be used
  35365. * @returns a boolean indicating that the submesh is ready or not
  35366. */
  35367. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35368. return false;
  35369. };
  35370. /**
  35371. * Returns the material effect
  35372. * @returns the effect associated with the material
  35373. */
  35374. Material.prototype.getEffect = function () {
  35375. return this._effect;
  35376. };
  35377. /**
  35378. * Returns the current scene
  35379. * @returns a Scene
  35380. */
  35381. Material.prototype.getScene = function () {
  35382. return this._scene;
  35383. };
  35384. /**
  35385. * Specifies if the material will require alpha blending
  35386. * @returns a boolean specifying if alpha blending is needed
  35387. */
  35388. Material.prototype.needAlphaBlending = function () {
  35389. return (this.alpha < 1.0);
  35390. };
  35391. /**
  35392. * Specifies if the mesh will require alpha blending
  35393. * @param mesh defines the mesh to check
  35394. * @returns a boolean specifying if alpha blending is needed for the mesh
  35395. */
  35396. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35397. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35398. };
  35399. /**
  35400. * Specifies if this material should be rendered in alpha test mode
  35401. * @returns a boolean specifying if an alpha test is needed.
  35402. */
  35403. Material.prototype.needAlphaTesting = function () {
  35404. return false;
  35405. };
  35406. /**
  35407. * Gets the texture used for the alpha test
  35408. * @returns the texture to use for alpha testing
  35409. */
  35410. Material.prototype.getAlphaTestTexture = function () {
  35411. return null;
  35412. };
  35413. /**
  35414. * Marks the material to indicate that it needs to be re-calculated
  35415. */
  35416. Material.prototype.markDirty = function () {
  35417. this._wasPreviouslyReady = false;
  35418. };
  35419. /** @hidden */
  35420. Material.prototype._preBind = function (effect, overrideOrientation) {
  35421. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35422. var engine = this._scene.getEngine();
  35423. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35424. var reverse = orientation === Material.ClockWiseSideOrientation;
  35425. engine.enableEffect(effect ? effect : this._effect);
  35426. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35427. return reverse;
  35428. };
  35429. /**
  35430. * Binds the material to the mesh
  35431. * @param world defines the world transformation matrix
  35432. * @param mesh defines the mesh to bind the material to
  35433. */
  35434. Material.prototype.bind = function (world, mesh) {
  35435. };
  35436. /**
  35437. * Binds the submesh to the material
  35438. * @param world defines the world transformation matrix
  35439. * @param mesh defines the mesh containing the submesh
  35440. * @param subMesh defines the submesh to bind the material to
  35441. */
  35442. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35443. };
  35444. /**
  35445. * Binds the world matrix to the material
  35446. * @param world defines the world transformation matrix
  35447. */
  35448. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35449. };
  35450. /**
  35451. * Binds the scene's uniform buffer to the effect.
  35452. * @param effect defines the effect to bind to the scene uniform buffer
  35453. * @param sceneUbo defines the uniform buffer storing scene data
  35454. */
  35455. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35456. sceneUbo.bindToEffect(effect, "Scene");
  35457. };
  35458. /**
  35459. * Binds the view matrix to the effect
  35460. * @param effect defines the effect to bind the view matrix to
  35461. */
  35462. Material.prototype.bindView = function (effect) {
  35463. if (!this._useUBO) {
  35464. effect.setMatrix("view", this.getScene().getViewMatrix());
  35465. }
  35466. else {
  35467. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35468. }
  35469. };
  35470. /**
  35471. * Binds the view projection matrix to the effect
  35472. * @param effect defines the effect to bind the view projection matrix to
  35473. */
  35474. Material.prototype.bindViewProjection = function (effect) {
  35475. if (!this._useUBO) {
  35476. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35477. }
  35478. else {
  35479. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35480. }
  35481. };
  35482. /**
  35483. * Specifies if material alpha testing should be turned on for the mesh
  35484. * @param mesh defines the mesh to check
  35485. */
  35486. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35487. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35488. };
  35489. /**
  35490. * Processes to execute after binding the material to a mesh
  35491. * @param mesh defines the rendered mesh
  35492. */
  35493. Material.prototype._afterBind = function (mesh) {
  35494. this._scene._cachedMaterial = this;
  35495. if (mesh) {
  35496. this._scene._cachedVisibility = mesh.visibility;
  35497. }
  35498. else {
  35499. this._scene._cachedVisibility = 1;
  35500. }
  35501. if (this._onBindObservable && mesh) {
  35502. this._onBindObservable.notifyObservers(mesh);
  35503. }
  35504. if (this.disableDepthWrite) {
  35505. var engine = this._scene.getEngine();
  35506. this._cachedDepthWriteState = engine.getDepthWrite();
  35507. engine.setDepthWrite(false);
  35508. }
  35509. };
  35510. /**
  35511. * Unbinds the material from the mesh
  35512. */
  35513. Material.prototype.unbind = function () {
  35514. if (this._onUnBindObservable) {
  35515. this._onUnBindObservable.notifyObservers(this);
  35516. }
  35517. if (this.disableDepthWrite) {
  35518. var engine = this._scene.getEngine();
  35519. engine.setDepthWrite(this._cachedDepthWriteState);
  35520. }
  35521. };
  35522. /**
  35523. * Gets the active textures from the material
  35524. * @returns an array of textures
  35525. */
  35526. Material.prototype.getActiveTextures = function () {
  35527. return [];
  35528. };
  35529. /**
  35530. * Specifies if the material uses a texture
  35531. * @param texture defines the texture to check against the material
  35532. * @returns a boolean specifying if the material uses the texture
  35533. */
  35534. Material.prototype.hasTexture = function (texture) {
  35535. return false;
  35536. };
  35537. /**
  35538. * Makes a duplicate of the material, and gives it a new name
  35539. * @param name defines the new name for the duplicated material
  35540. * @returns the cloned material
  35541. */
  35542. Material.prototype.clone = function (name) {
  35543. return null;
  35544. };
  35545. /**
  35546. * Gets the meshes bound to the material
  35547. * @returns an array of meshes bound to the material
  35548. */
  35549. Material.prototype.getBindedMeshes = function () {
  35550. var result = new Array();
  35551. for (var index = 0; index < this._scene.meshes.length; index++) {
  35552. var mesh = this._scene.meshes[index];
  35553. if (mesh.material === this) {
  35554. result.push(mesh);
  35555. }
  35556. }
  35557. return result;
  35558. };
  35559. /**
  35560. * Force shader compilation
  35561. * @param mesh defines the mesh associated with this material
  35562. * @param onCompiled defines a function to execute once the material is compiled
  35563. * @param options defines the options to configure the compilation
  35564. */
  35565. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35566. var _this = this;
  35567. var localOptions = __assign({ clipPlane: false }, options);
  35568. var subMesh = new BABYLON.BaseSubMesh();
  35569. var scene = this.getScene();
  35570. var checkReady = function () {
  35571. if (!_this._scene || !_this._scene.getEngine()) {
  35572. return;
  35573. }
  35574. if (subMesh._materialDefines) {
  35575. subMesh._materialDefines._renderId = -1;
  35576. }
  35577. var clipPlaneState = scene.clipPlane;
  35578. if (localOptions.clipPlane) {
  35579. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35580. }
  35581. if (_this.storeEffectOnSubMeshes) {
  35582. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35583. if (onCompiled) {
  35584. onCompiled(_this);
  35585. }
  35586. }
  35587. else {
  35588. setTimeout(checkReady, 16);
  35589. }
  35590. }
  35591. else {
  35592. if (_this.isReady(mesh)) {
  35593. if (onCompiled) {
  35594. onCompiled(_this);
  35595. }
  35596. }
  35597. else {
  35598. setTimeout(checkReady, 16);
  35599. }
  35600. }
  35601. if (localOptions.clipPlane) {
  35602. scene.clipPlane = clipPlaneState;
  35603. }
  35604. };
  35605. checkReady();
  35606. };
  35607. /**
  35608. * Force shader compilation
  35609. * @param mesh defines the mesh that will use this material
  35610. * @param options defines additional options for compiling the shaders
  35611. * @returns a promise that resolves when the compilation completes
  35612. */
  35613. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35614. var _this = this;
  35615. return new Promise(function (resolve) {
  35616. _this.forceCompilation(mesh, function () {
  35617. resolve();
  35618. }, options);
  35619. });
  35620. };
  35621. /**
  35622. * Marks a define in the material to indicate that it needs to be re-computed
  35623. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35624. */
  35625. Material.prototype.markAsDirty = function (flag) {
  35626. if (flag & Material.TextureDirtyFlag) {
  35627. this._markAllSubMeshesAsTexturesDirty();
  35628. }
  35629. if (flag & Material.LightDirtyFlag) {
  35630. this._markAllSubMeshesAsLightsDirty();
  35631. }
  35632. if (flag & Material.FresnelDirtyFlag) {
  35633. this._markAllSubMeshesAsFresnelDirty();
  35634. }
  35635. if (flag & Material.AttributesDirtyFlag) {
  35636. this._markAllSubMeshesAsAttributesDirty();
  35637. }
  35638. if (flag & Material.MiscDirtyFlag) {
  35639. this._markAllSubMeshesAsMiscDirty();
  35640. }
  35641. this.getScene().resetCachedMaterial();
  35642. };
  35643. /**
  35644. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35645. * @param func defines a function which checks material defines against the submeshes
  35646. */
  35647. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35648. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35649. var mesh = _a[_i];
  35650. if (!mesh.subMeshes) {
  35651. continue;
  35652. }
  35653. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35654. var subMesh = _c[_b];
  35655. if (subMesh.getMaterial() !== this) {
  35656. continue;
  35657. }
  35658. if (!subMesh._materialDefines) {
  35659. continue;
  35660. }
  35661. func(subMesh._materialDefines);
  35662. }
  35663. }
  35664. };
  35665. /**
  35666. * Indicates that image processing needs to be re-calculated for all submeshes
  35667. */
  35668. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35669. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35670. };
  35671. /**
  35672. * Indicates that textures need to be re-calculated for all submeshes
  35673. */
  35674. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35675. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35676. };
  35677. /**
  35678. * Indicates that fresnel needs to be re-calculated for all submeshes
  35679. */
  35680. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35681. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35682. };
  35683. /**
  35684. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35685. */
  35686. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35687. this._markAllSubMeshesAsDirty(function (defines) {
  35688. defines.markAsFresnelDirty();
  35689. defines.markAsMiscDirty();
  35690. });
  35691. };
  35692. /**
  35693. * Indicates that lights need to be re-calculated for all submeshes
  35694. */
  35695. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35696. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35697. };
  35698. /**
  35699. * Indicates that attributes need to be re-calculated for all submeshes
  35700. */
  35701. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35702. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35703. };
  35704. /**
  35705. * Indicates that misc needs to be re-calculated for all submeshes
  35706. */
  35707. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35708. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35709. };
  35710. /**
  35711. * Indicates that textures and misc need to be re-calculated for all submeshes
  35712. */
  35713. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35714. this._markAllSubMeshesAsDirty(function (defines) {
  35715. defines.markAsTexturesDirty();
  35716. defines.markAsMiscDirty();
  35717. });
  35718. };
  35719. /**
  35720. * Disposes the material
  35721. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35722. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35723. */
  35724. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35725. // Animations
  35726. this.getScene().stopAnimation(this);
  35727. this.getScene().freeProcessedMaterials();
  35728. // Remove from scene
  35729. var index = this._scene.materials.indexOf(this);
  35730. if (index >= 0) {
  35731. this._scene.materials.splice(index, 1);
  35732. }
  35733. // Remove from meshes
  35734. for (index = 0; index < this._scene.meshes.length; index++) {
  35735. var mesh = this._scene.meshes[index];
  35736. if (mesh.material === this) {
  35737. mesh.material = null;
  35738. if (mesh.geometry) {
  35739. var geometry = (mesh.geometry);
  35740. if (this.storeEffectOnSubMeshes) {
  35741. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35742. var subMesh = _a[_i];
  35743. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35744. if (forceDisposeEffect && subMesh._materialEffect) {
  35745. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35746. }
  35747. }
  35748. }
  35749. else {
  35750. geometry._releaseVertexArrayObject(this._effect);
  35751. }
  35752. }
  35753. }
  35754. }
  35755. this._uniformBuffer.dispose();
  35756. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35757. if (forceDisposeEffect && this._effect) {
  35758. if (!this.storeEffectOnSubMeshes) {
  35759. this._scene.getEngine()._releaseEffect(this._effect);
  35760. }
  35761. this._effect = null;
  35762. }
  35763. // Callback
  35764. this.onDisposeObservable.notifyObservers(this);
  35765. this.onDisposeObservable.clear();
  35766. if (this._onBindObservable) {
  35767. this._onBindObservable.clear();
  35768. }
  35769. if (this._onUnBindObservable) {
  35770. this._onUnBindObservable.clear();
  35771. }
  35772. };
  35773. /**
  35774. * Serializes this material
  35775. * @returns the serialized material object
  35776. */
  35777. Material.prototype.serialize = function () {
  35778. return BABYLON.SerializationHelper.Serialize(this);
  35779. };
  35780. /**
  35781. * Creates a MultiMaterial from parsed MultiMaterial data.
  35782. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35783. * @param scene defines the hosting scene
  35784. * @returns a new MultiMaterial
  35785. */
  35786. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35787. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35788. multiMaterial.id = parsedMultiMaterial.id;
  35789. if (BABYLON.Tags) {
  35790. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35791. }
  35792. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35793. var subMatId = parsedMultiMaterial.materials[matIndex];
  35794. if (subMatId) {
  35795. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35796. }
  35797. else {
  35798. multiMaterial.subMaterials.push(null);
  35799. }
  35800. }
  35801. return multiMaterial;
  35802. };
  35803. /**
  35804. * Creates a material from parsed material data
  35805. * @param parsedMaterial defines parsed material data
  35806. * @param scene defines the hosting scene
  35807. * @param rootUrl defines the root URL to use to load textures
  35808. * @returns a new material
  35809. */
  35810. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35811. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35812. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35813. }
  35814. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35815. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35816. if (!BABYLON.LegacyPBRMaterial) {
  35817. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35818. return;
  35819. }
  35820. }
  35821. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35822. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35823. };
  35824. // Triangle views
  35825. Material._TriangleFillMode = 0;
  35826. Material._WireFrameFillMode = 1;
  35827. Material._PointFillMode = 2;
  35828. // Draw modes
  35829. Material._PointListDrawMode = 3;
  35830. Material._LineListDrawMode = 4;
  35831. Material._LineLoopDrawMode = 5;
  35832. Material._LineStripDrawMode = 6;
  35833. Material._TriangleStripDrawMode = 7;
  35834. Material._TriangleFanDrawMode = 8;
  35835. /**
  35836. * Stores the clock-wise side orientation
  35837. */
  35838. Material._ClockWiseSideOrientation = 0;
  35839. /**
  35840. * Stores the counter clock-wise side orientation
  35841. */
  35842. Material._CounterClockWiseSideOrientation = 1;
  35843. /**
  35844. * The dirty texture flag value
  35845. */
  35846. Material._TextureDirtyFlag = 1;
  35847. /**
  35848. * The dirty light flag value
  35849. */
  35850. Material._LightDirtyFlag = 2;
  35851. /**
  35852. * The dirty fresnel flag value
  35853. */
  35854. Material._FresnelDirtyFlag = 4;
  35855. /**
  35856. * The dirty attribute flag value
  35857. */
  35858. Material._AttributesDirtyFlag = 8;
  35859. /**
  35860. * The dirty misc flag value
  35861. */
  35862. Material._MiscDirtyFlag = 16;
  35863. __decorate([
  35864. BABYLON.serialize()
  35865. ], Material.prototype, "id", void 0);
  35866. __decorate([
  35867. BABYLON.serialize()
  35868. ], Material.prototype, "uniqueId", void 0);
  35869. __decorate([
  35870. BABYLON.serialize()
  35871. ], Material.prototype, "name", void 0);
  35872. __decorate([
  35873. BABYLON.serialize()
  35874. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35875. __decorate([
  35876. BABYLON.serialize()
  35877. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35878. __decorate([
  35879. BABYLON.serialize()
  35880. ], Material.prototype, "state", void 0);
  35881. __decorate([
  35882. BABYLON.serialize("alpha")
  35883. ], Material.prototype, "_alpha", void 0);
  35884. __decorate([
  35885. BABYLON.serialize("backFaceCulling")
  35886. ], Material.prototype, "_backFaceCulling", void 0);
  35887. __decorate([
  35888. BABYLON.serialize()
  35889. ], Material.prototype, "sideOrientation", void 0);
  35890. __decorate([
  35891. BABYLON.serialize("alphaMode")
  35892. ], Material.prototype, "_alphaMode", void 0);
  35893. __decorate([
  35894. BABYLON.serialize()
  35895. ], Material.prototype, "_needDepthPrePass", void 0);
  35896. __decorate([
  35897. BABYLON.serialize()
  35898. ], Material.prototype, "disableDepthWrite", void 0);
  35899. __decorate([
  35900. BABYLON.serialize()
  35901. ], Material.prototype, "forceDepthWrite", void 0);
  35902. __decorate([
  35903. BABYLON.serialize()
  35904. ], Material.prototype, "separateCullingPass", void 0);
  35905. __decorate([
  35906. BABYLON.serialize("fogEnabled")
  35907. ], Material.prototype, "_fogEnabled", void 0);
  35908. __decorate([
  35909. BABYLON.serialize()
  35910. ], Material.prototype, "pointSize", void 0);
  35911. __decorate([
  35912. BABYLON.serialize()
  35913. ], Material.prototype, "zOffset", void 0);
  35914. __decorate([
  35915. BABYLON.serialize()
  35916. ], Material.prototype, "wireframe", null);
  35917. __decorate([
  35918. BABYLON.serialize()
  35919. ], Material.prototype, "pointsCloud", null);
  35920. __decorate([
  35921. BABYLON.serialize()
  35922. ], Material.prototype, "fillMode", null);
  35923. return Material;
  35924. }());
  35925. BABYLON.Material = Material;
  35926. })(BABYLON || (BABYLON = {}));
  35927. //# sourceMappingURL=babylon.material.js.map
  35928. var BABYLON;
  35929. (function (BABYLON) {
  35930. var UniformBuffer = /** @class */ (function () {
  35931. /**
  35932. * Uniform buffer objects.
  35933. *
  35934. * Handles blocks of uniform on the GPU.
  35935. *
  35936. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35937. *
  35938. * For more information, please refer to :
  35939. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35940. */
  35941. function UniformBuffer(engine, data, dynamic) {
  35942. this._engine = engine;
  35943. this._noUBO = !engine.supportsUniformBuffers;
  35944. this._dynamic = dynamic;
  35945. this._data = data || [];
  35946. this._uniformLocations = {};
  35947. this._uniformSizes = {};
  35948. this._uniformLocationPointer = 0;
  35949. this._needSync = false;
  35950. if (this._noUBO) {
  35951. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35952. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35953. this.updateFloat = this._updateFloatForEffect;
  35954. this.updateFloat2 = this._updateFloat2ForEffect;
  35955. this.updateFloat3 = this._updateFloat3ForEffect;
  35956. this.updateFloat4 = this._updateFloat4ForEffect;
  35957. this.updateMatrix = this._updateMatrixForEffect;
  35958. this.updateVector3 = this._updateVector3ForEffect;
  35959. this.updateVector4 = this._updateVector4ForEffect;
  35960. this.updateColor3 = this._updateColor3ForEffect;
  35961. this.updateColor4 = this._updateColor4ForEffect;
  35962. }
  35963. else {
  35964. this._engine._uniformBuffers.push(this);
  35965. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35966. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35967. this.updateFloat = this._updateFloatForUniform;
  35968. this.updateFloat2 = this._updateFloat2ForUniform;
  35969. this.updateFloat3 = this._updateFloat3ForUniform;
  35970. this.updateFloat4 = this._updateFloat4ForUniform;
  35971. this.updateMatrix = this._updateMatrixForUniform;
  35972. this.updateVector3 = this._updateVector3ForUniform;
  35973. this.updateVector4 = this._updateVector4ForUniform;
  35974. this.updateColor3 = this._updateColor3ForUniform;
  35975. this.updateColor4 = this._updateColor4ForUniform;
  35976. }
  35977. }
  35978. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35979. // Properties
  35980. /**
  35981. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35982. * or just falling back on setUniformXXX calls.
  35983. */
  35984. get: function () {
  35985. return !this._noUBO;
  35986. },
  35987. enumerable: true,
  35988. configurable: true
  35989. });
  35990. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35991. /**
  35992. * Indicates if the WebGL underlying uniform buffer is in sync
  35993. * with the javascript cache data.
  35994. */
  35995. get: function () {
  35996. return !this._needSync;
  35997. },
  35998. enumerable: true,
  35999. configurable: true
  36000. });
  36001. /**
  36002. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36003. * Also, a dynamic UniformBuffer will disable cache verification and always
  36004. * update the underlying WebGL uniform buffer to the GPU.
  36005. */
  36006. UniformBuffer.prototype.isDynamic = function () {
  36007. return this._dynamic !== undefined;
  36008. };
  36009. /**
  36010. * The data cache on JS side.
  36011. */
  36012. UniformBuffer.prototype.getData = function () {
  36013. return this._bufferData;
  36014. };
  36015. /**
  36016. * The underlying WebGL Uniform buffer.
  36017. */
  36018. UniformBuffer.prototype.getBuffer = function () {
  36019. return this._buffer;
  36020. };
  36021. /**
  36022. * std140 layout specifies how to align data within an UBO structure.
  36023. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36024. * for specs.
  36025. */
  36026. UniformBuffer.prototype._fillAlignment = function (size) {
  36027. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36028. // and 4x4 matrices
  36029. // TODO : change if other types are used
  36030. var alignment;
  36031. if (size <= 2) {
  36032. alignment = size;
  36033. }
  36034. else {
  36035. alignment = 4;
  36036. }
  36037. if ((this._uniformLocationPointer % alignment) !== 0) {
  36038. var oldPointer = this._uniformLocationPointer;
  36039. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36040. var diff = this._uniformLocationPointer - oldPointer;
  36041. for (var i = 0; i < diff; i++) {
  36042. this._data.push(0);
  36043. }
  36044. }
  36045. };
  36046. /**
  36047. * Adds an uniform in the buffer.
  36048. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36049. * for the layout to be correct !
  36050. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36051. * @param {number|number[]} size Data size, or data directly.
  36052. */
  36053. UniformBuffer.prototype.addUniform = function (name, size) {
  36054. if (this._noUBO) {
  36055. return;
  36056. }
  36057. if (this._uniformLocations[name] !== undefined) {
  36058. // Already existing uniform
  36059. return;
  36060. }
  36061. // This function must be called in the order of the shader layout !
  36062. // size can be the size of the uniform, or data directly
  36063. var data;
  36064. if (size instanceof Array) {
  36065. data = size;
  36066. size = data.length;
  36067. }
  36068. else {
  36069. size = size;
  36070. data = [];
  36071. // Fill with zeros
  36072. for (var i = 0; i < size; i++) {
  36073. data.push(0);
  36074. }
  36075. }
  36076. this._fillAlignment(size);
  36077. this._uniformSizes[name] = size;
  36078. this._uniformLocations[name] = this._uniformLocationPointer;
  36079. this._uniformLocationPointer += size;
  36080. for (var i = 0; i < size; i++) {
  36081. this._data.push(data[i]);
  36082. }
  36083. this._needSync = true;
  36084. };
  36085. /**
  36086. * Wrapper for addUniform.
  36087. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36088. * @param {Matrix} mat A 4x4 matrix.
  36089. */
  36090. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36091. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36092. };
  36093. /**
  36094. * Wrapper for addUniform.
  36095. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36096. * @param {number} x
  36097. * @param {number} y
  36098. */
  36099. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36100. var temp = [x, y];
  36101. this.addUniform(name, temp);
  36102. };
  36103. /**
  36104. * Wrapper for addUniform.
  36105. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36106. * @param {number} x
  36107. * @param {number} y
  36108. * @param {number} z
  36109. */
  36110. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36111. var temp = [x, y, z];
  36112. this.addUniform(name, temp);
  36113. };
  36114. /**
  36115. * Wrapper for addUniform.
  36116. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36117. * @param {Color3} color
  36118. */
  36119. UniformBuffer.prototype.addColor3 = function (name, color) {
  36120. var temp = new Array();
  36121. color.toArray(temp);
  36122. this.addUniform(name, temp);
  36123. };
  36124. /**
  36125. * Wrapper for addUniform.
  36126. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36127. * @param {Color3} color
  36128. * @param {number} alpha
  36129. */
  36130. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36131. var temp = new Array();
  36132. color.toArray(temp);
  36133. temp.push(alpha);
  36134. this.addUniform(name, temp);
  36135. };
  36136. /**
  36137. * Wrapper for addUniform.
  36138. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36139. * @param {Vector3} vector
  36140. */
  36141. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36142. var temp = new Array();
  36143. vector.toArray(temp);
  36144. this.addUniform(name, temp);
  36145. };
  36146. /**
  36147. * Wrapper for addUniform.
  36148. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36149. */
  36150. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36151. this.addUniform(name, 12);
  36152. };
  36153. /**
  36154. * Wrapper for addUniform.
  36155. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36156. */
  36157. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36158. this.addUniform(name, 8);
  36159. };
  36160. /**
  36161. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36162. */
  36163. UniformBuffer.prototype.create = function () {
  36164. if (this._noUBO) {
  36165. return;
  36166. }
  36167. if (this._buffer) {
  36168. return; // nothing to do
  36169. }
  36170. // See spec, alignment must be filled as a vec4
  36171. this._fillAlignment(4);
  36172. this._bufferData = new Float32Array(this._data);
  36173. this._rebuild();
  36174. this._needSync = true;
  36175. };
  36176. /** @hidden */
  36177. UniformBuffer.prototype._rebuild = function () {
  36178. if (this._noUBO) {
  36179. return;
  36180. }
  36181. if (this._dynamic) {
  36182. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36183. }
  36184. else {
  36185. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36186. }
  36187. };
  36188. /**
  36189. * Updates the WebGL Uniform Buffer on the GPU.
  36190. * If the `dynamic` flag is set to true, no cache comparison is done.
  36191. * Otherwise, the buffer will be updated only if the cache differs.
  36192. */
  36193. UniformBuffer.prototype.update = function () {
  36194. if (!this._buffer) {
  36195. this.create();
  36196. return;
  36197. }
  36198. if (!this._dynamic && !this._needSync) {
  36199. return;
  36200. }
  36201. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36202. this._needSync = false;
  36203. };
  36204. /**
  36205. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36206. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36207. * @param {number[]|Float32Array} data Flattened data
  36208. * @param {number} size Size of the data.
  36209. */
  36210. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36211. var location = this._uniformLocations[uniformName];
  36212. if (location === undefined) {
  36213. if (this._buffer) {
  36214. // Cannot add an uniform if the buffer is already created
  36215. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36216. return;
  36217. }
  36218. this.addUniform(uniformName, size);
  36219. location = this._uniformLocations[uniformName];
  36220. }
  36221. if (!this._buffer) {
  36222. this.create();
  36223. }
  36224. if (!this._dynamic) {
  36225. // Cache for static uniform buffers
  36226. var changed = false;
  36227. for (var i = 0; i < size; i++) {
  36228. if (this._bufferData[location + i] !== data[i]) {
  36229. changed = true;
  36230. this._bufferData[location + i] = data[i];
  36231. }
  36232. }
  36233. this._needSync = this._needSync || changed;
  36234. }
  36235. else {
  36236. // No cache for dynamic
  36237. for (var i = 0; i < size; i++) {
  36238. this._bufferData[location + i] = data[i];
  36239. }
  36240. }
  36241. };
  36242. // Update methods
  36243. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36244. // To match std140, matrix must be realigned
  36245. for (var i = 0; i < 3; i++) {
  36246. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36247. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36248. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36249. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36250. }
  36251. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36252. };
  36253. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36254. this._currentEffect.setMatrix3x3(name, matrix);
  36255. };
  36256. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36257. this._currentEffect.setMatrix2x2(name, matrix);
  36258. };
  36259. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36260. // To match std140, matrix must be realigned
  36261. for (var i = 0; i < 2; i++) {
  36262. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36263. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36264. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36265. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36266. }
  36267. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36268. };
  36269. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36270. this._currentEffect.setFloat(name, x);
  36271. };
  36272. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36273. UniformBuffer._tempBuffer[0] = x;
  36274. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36275. };
  36276. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36277. if (suffix === void 0) { suffix = ""; }
  36278. this._currentEffect.setFloat2(name + suffix, x, y);
  36279. };
  36280. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36281. if (suffix === void 0) { suffix = ""; }
  36282. UniformBuffer._tempBuffer[0] = x;
  36283. UniformBuffer._tempBuffer[1] = y;
  36284. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36285. };
  36286. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36287. if (suffix === void 0) { suffix = ""; }
  36288. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36289. };
  36290. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36291. if (suffix === void 0) { suffix = ""; }
  36292. UniformBuffer._tempBuffer[0] = x;
  36293. UniformBuffer._tempBuffer[1] = y;
  36294. UniformBuffer._tempBuffer[2] = z;
  36295. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36296. };
  36297. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36298. if (suffix === void 0) { suffix = ""; }
  36299. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36300. };
  36301. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36302. if (suffix === void 0) { suffix = ""; }
  36303. UniformBuffer._tempBuffer[0] = x;
  36304. UniformBuffer._tempBuffer[1] = y;
  36305. UniformBuffer._tempBuffer[2] = z;
  36306. UniformBuffer._tempBuffer[3] = w;
  36307. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36308. };
  36309. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36310. this._currentEffect.setMatrix(name, mat);
  36311. };
  36312. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36313. this.updateUniform(name, mat.toArray(), 16);
  36314. };
  36315. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36316. this._currentEffect.setVector3(name, vector);
  36317. };
  36318. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36319. vector.toArray(UniformBuffer._tempBuffer);
  36320. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36321. };
  36322. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36323. this._currentEffect.setVector4(name, vector);
  36324. };
  36325. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36326. vector.toArray(UniformBuffer._tempBuffer);
  36327. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36328. };
  36329. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36330. if (suffix === void 0) { suffix = ""; }
  36331. this._currentEffect.setColor3(name + suffix, color);
  36332. };
  36333. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36334. if (suffix === void 0) { suffix = ""; }
  36335. color.toArray(UniformBuffer._tempBuffer);
  36336. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36337. };
  36338. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36339. if (suffix === void 0) { suffix = ""; }
  36340. this._currentEffect.setColor4(name + suffix, color, alpha);
  36341. };
  36342. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36343. if (suffix === void 0) { suffix = ""; }
  36344. color.toArray(UniformBuffer._tempBuffer);
  36345. UniformBuffer._tempBuffer[3] = alpha;
  36346. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36347. };
  36348. /**
  36349. * Sets a sampler uniform on the effect.
  36350. * @param {string} name Name of the sampler.
  36351. * @param {Texture} texture
  36352. */
  36353. UniformBuffer.prototype.setTexture = function (name, texture) {
  36354. this._currentEffect.setTexture(name, texture);
  36355. };
  36356. /**
  36357. * Directly updates the value of the uniform in the cache AND on the GPU.
  36358. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36359. * @param {number[]|Float32Array} data Flattened data
  36360. */
  36361. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36362. this.updateUniform(uniformName, data, data.length);
  36363. this.update();
  36364. };
  36365. /**
  36366. * Binds this uniform buffer to an effect.
  36367. * @param {Effect} effect
  36368. * @param {string} name Name of the uniform block in the shader.
  36369. */
  36370. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36371. this._currentEffect = effect;
  36372. if (this._noUBO || !this._buffer) {
  36373. return;
  36374. }
  36375. effect.bindUniformBuffer(this._buffer, name);
  36376. };
  36377. /**
  36378. * Disposes the uniform buffer.
  36379. */
  36380. UniformBuffer.prototype.dispose = function () {
  36381. if (this._noUBO) {
  36382. return;
  36383. }
  36384. var index = this._engine._uniformBuffers.indexOf(this);
  36385. if (index !== -1) {
  36386. this._engine._uniformBuffers.splice(index, 1);
  36387. }
  36388. if (!this._buffer) {
  36389. return;
  36390. }
  36391. if (this._engine._releaseBuffer(this._buffer)) {
  36392. this._buffer = null;
  36393. }
  36394. };
  36395. // Pool for avoiding memory leaks
  36396. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36397. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36398. return UniformBuffer;
  36399. }());
  36400. BABYLON.UniformBuffer = UniformBuffer;
  36401. })(BABYLON || (BABYLON = {}));
  36402. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36403. var BABYLON;
  36404. (function (BABYLON) {
  36405. /**
  36406. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36407. */
  36408. var VertexData = /** @class */ (function () {
  36409. function VertexData() {
  36410. }
  36411. /**
  36412. * Uses the passed data array to set the set the values for the specified kind of data
  36413. * @param data a linear array of floating numbers
  36414. * @param kind the type of data that is being set, eg positions, colors etc
  36415. */
  36416. VertexData.prototype.set = function (data, kind) {
  36417. switch (kind) {
  36418. case BABYLON.VertexBuffer.PositionKind:
  36419. this.positions = data;
  36420. break;
  36421. case BABYLON.VertexBuffer.NormalKind:
  36422. this.normals = data;
  36423. break;
  36424. case BABYLON.VertexBuffer.TangentKind:
  36425. this.tangents = data;
  36426. break;
  36427. case BABYLON.VertexBuffer.UVKind:
  36428. this.uvs = data;
  36429. break;
  36430. case BABYLON.VertexBuffer.UV2Kind:
  36431. this.uvs2 = data;
  36432. break;
  36433. case BABYLON.VertexBuffer.UV3Kind:
  36434. this.uvs3 = data;
  36435. break;
  36436. case BABYLON.VertexBuffer.UV4Kind:
  36437. this.uvs4 = data;
  36438. break;
  36439. case BABYLON.VertexBuffer.UV5Kind:
  36440. this.uvs5 = data;
  36441. break;
  36442. case BABYLON.VertexBuffer.UV6Kind:
  36443. this.uvs6 = data;
  36444. break;
  36445. case BABYLON.VertexBuffer.ColorKind:
  36446. this.colors = data;
  36447. break;
  36448. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36449. this.matricesIndices = data;
  36450. break;
  36451. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36452. this.matricesWeights = data;
  36453. break;
  36454. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36455. this.matricesIndicesExtra = data;
  36456. break;
  36457. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36458. this.matricesWeightsExtra = data;
  36459. break;
  36460. }
  36461. };
  36462. /**
  36463. * Associates the vertexData to the passed Mesh.
  36464. * Sets it as updatable or not (default `false`)
  36465. * @param mesh the mesh the vertexData is applied to
  36466. * @param updatable when used and having the value true allows new data to update the vertexData
  36467. * @returns the VertexData
  36468. */
  36469. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36470. this._applyTo(mesh, updatable);
  36471. return this;
  36472. };
  36473. /**
  36474. * Associates the vertexData to the passed Geometry.
  36475. * Sets it as updatable or not (default `false`)
  36476. * @param geometry the geometry the vertexData is applied to
  36477. * @param updatable when used and having the value true allows new data to update the vertexData
  36478. * @returns VertexData
  36479. */
  36480. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36481. this._applyTo(geometry, updatable);
  36482. return this;
  36483. };
  36484. /**
  36485. * Updates the associated mesh
  36486. * @param mesh the mesh to be updated
  36487. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36488. * @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
  36489. * @returns VertexData
  36490. */
  36491. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36492. this._update(mesh);
  36493. return this;
  36494. };
  36495. /**
  36496. * Updates the associated geometry
  36497. * @param geometry the geometry to be updated
  36498. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36499. * @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
  36500. * @returns VertexData.
  36501. */
  36502. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36503. this._update(geometry);
  36504. return this;
  36505. };
  36506. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36507. if (updatable === void 0) { updatable = false; }
  36508. if (this.positions) {
  36509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36510. }
  36511. if (this.normals) {
  36512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36513. }
  36514. if (this.tangents) {
  36515. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36516. }
  36517. if (this.uvs) {
  36518. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36519. }
  36520. if (this.uvs2) {
  36521. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36522. }
  36523. if (this.uvs3) {
  36524. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36525. }
  36526. if (this.uvs4) {
  36527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36528. }
  36529. if (this.uvs5) {
  36530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36531. }
  36532. if (this.uvs6) {
  36533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36534. }
  36535. if (this.colors) {
  36536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36537. }
  36538. if (this.matricesIndices) {
  36539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36540. }
  36541. if (this.matricesWeights) {
  36542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36543. }
  36544. if (this.matricesIndicesExtra) {
  36545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36546. }
  36547. if (this.matricesWeightsExtra) {
  36548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36549. }
  36550. if (this.indices) {
  36551. meshOrGeometry.setIndices(this.indices, null, updatable);
  36552. }
  36553. else {
  36554. meshOrGeometry.setIndices([], null);
  36555. }
  36556. return this;
  36557. };
  36558. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36559. if (this.positions) {
  36560. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36561. }
  36562. if (this.normals) {
  36563. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36564. }
  36565. if (this.tangents) {
  36566. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36567. }
  36568. if (this.uvs) {
  36569. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36570. }
  36571. if (this.uvs2) {
  36572. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36573. }
  36574. if (this.uvs3) {
  36575. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36576. }
  36577. if (this.uvs4) {
  36578. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36579. }
  36580. if (this.uvs5) {
  36581. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36582. }
  36583. if (this.uvs6) {
  36584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36585. }
  36586. if (this.colors) {
  36587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36588. }
  36589. if (this.matricesIndices) {
  36590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36591. }
  36592. if (this.matricesWeights) {
  36593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36594. }
  36595. if (this.matricesIndicesExtra) {
  36596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36597. }
  36598. if (this.matricesWeightsExtra) {
  36599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36600. }
  36601. if (this.indices) {
  36602. meshOrGeometry.setIndices(this.indices, null);
  36603. }
  36604. return this;
  36605. };
  36606. /**
  36607. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36608. * @param matrix the transforming matrix
  36609. * @returns the VertexData
  36610. */
  36611. VertexData.prototype.transform = function (matrix) {
  36612. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36613. var transformed = BABYLON.Vector3.Zero();
  36614. var index;
  36615. if (this.positions) {
  36616. var position = BABYLON.Vector3.Zero();
  36617. for (index = 0; index < this.positions.length; index += 3) {
  36618. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36619. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36620. this.positions[index] = transformed.x;
  36621. this.positions[index + 1] = transformed.y;
  36622. this.positions[index + 2] = transformed.z;
  36623. }
  36624. }
  36625. if (this.normals) {
  36626. var normal = BABYLON.Vector3.Zero();
  36627. for (index = 0; index < this.normals.length; index += 3) {
  36628. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36629. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36630. this.normals[index] = transformed.x;
  36631. this.normals[index + 1] = transformed.y;
  36632. this.normals[index + 2] = transformed.z;
  36633. }
  36634. }
  36635. if (this.tangents) {
  36636. var tangent = BABYLON.Vector4.Zero();
  36637. var tangentTransformed = BABYLON.Vector4.Zero();
  36638. for (index = 0; index < this.tangents.length; index += 4) {
  36639. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36640. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36641. this.tangents[index] = tangentTransformed.x;
  36642. this.tangents[index + 1] = tangentTransformed.y;
  36643. this.tangents[index + 2] = tangentTransformed.z;
  36644. this.tangents[index + 3] = tangentTransformed.w;
  36645. }
  36646. }
  36647. if (flip && this.indices) {
  36648. for (index = 0; index < this.indices.length; index += 3) {
  36649. var tmp = this.indices[index + 1];
  36650. this.indices[index + 1] = this.indices[index + 2];
  36651. this.indices[index + 2] = tmp;
  36652. }
  36653. }
  36654. return this;
  36655. };
  36656. /**
  36657. * Merges the passed VertexData into the current one
  36658. * @param other the VertexData to be merged into the current one
  36659. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36660. * @returns the modified VertexData
  36661. */
  36662. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36663. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36664. this._validate();
  36665. other._validate();
  36666. if (!this.normals !== !other.normals ||
  36667. !this.tangents !== !other.tangents ||
  36668. !this.uvs !== !other.uvs ||
  36669. !this.uvs2 !== !other.uvs2 ||
  36670. !this.uvs3 !== !other.uvs3 ||
  36671. !this.uvs4 !== !other.uvs4 ||
  36672. !this.uvs5 !== !other.uvs5 ||
  36673. !this.uvs6 !== !other.uvs6 ||
  36674. !this.colors !== !other.colors ||
  36675. !this.matricesIndices !== !other.matricesIndices ||
  36676. !this.matricesWeights !== !other.matricesWeights ||
  36677. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36678. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36679. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36680. }
  36681. if (other.indices) {
  36682. if (!this.indices) {
  36683. this.indices = [];
  36684. }
  36685. var offset = this.positions ? this.positions.length / 3 : 0;
  36686. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36687. if (isSrcTypedArray) {
  36688. var len = this.indices.length + other.indices.length;
  36689. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36690. temp.set(this.indices);
  36691. var decal = this.indices.length;
  36692. for (var index = 0; index < other.indices.length; index++) {
  36693. temp[decal + index] = other.indices[index] + offset;
  36694. }
  36695. this.indices = temp;
  36696. }
  36697. else {
  36698. for (var index = 0; index < other.indices.length; index++) {
  36699. this.indices.push(other.indices[index] + offset);
  36700. }
  36701. }
  36702. }
  36703. this.positions = this._mergeElement(this.positions, other.positions);
  36704. this.normals = this._mergeElement(this.normals, other.normals);
  36705. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36706. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36707. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36708. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36709. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36710. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36711. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36712. this.colors = this._mergeElement(this.colors, other.colors);
  36713. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36714. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36715. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36716. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36717. return this;
  36718. };
  36719. VertexData.prototype._mergeElement = function (source, other) {
  36720. if (!source) {
  36721. return other;
  36722. }
  36723. if (!other) {
  36724. return source;
  36725. }
  36726. var len = other.length + source.length;
  36727. var isSrcTypedArray = source instanceof Float32Array;
  36728. var isOthTypedArray = other instanceof Float32Array;
  36729. // use non-loop method when the source is Float32Array
  36730. if (isSrcTypedArray) {
  36731. var ret32 = new Float32Array(len);
  36732. ret32.set(source);
  36733. ret32.set(other, source.length);
  36734. return ret32;
  36735. // source is number[], when other is also use concat
  36736. }
  36737. else if (!isOthTypedArray) {
  36738. return source.concat(other);
  36739. // source is a number[], but other is a Float32Array, loop required
  36740. }
  36741. else {
  36742. var ret = source.slice(0); // copy source to a separate array
  36743. for (var i = 0, len = other.length; i < len; i++) {
  36744. ret.push(other[i]);
  36745. }
  36746. return ret;
  36747. }
  36748. };
  36749. VertexData.prototype._validate = function () {
  36750. if (!this.positions) {
  36751. throw new Error("Positions are required");
  36752. }
  36753. var getElementCount = function (kind, values) {
  36754. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36755. if ((values.length % stride) !== 0) {
  36756. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36757. }
  36758. return values.length / stride;
  36759. };
  36760. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36761. var validateElementCount = function (kind, values) {
  36762. var elementCount = getElementCount(kind, values);
  36763. if (elementCount !== positionsElementCount) {
  36764. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36765. }
  36766. };
  36767. if (this.normals)
  36768. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36769. if (this.tangents)
  36770. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36771. if (this.uvs)
  36772. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36773. if (this.uvs2)
  36774. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36775. if (this.uvs3)
  36776. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36777. if (this.uvs4)
  36778. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36779. if (this.uvs5)
  36780. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36781. if (this.uvs6)
  36782. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36783. if (this.colors)
  36784. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36785. if (this.matricesIndices)
  36786. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36787. if (this.matricesWeights)
  36788. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36789. if (this.matricesIndicesExtra)
  36790. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36791. if (this.matricesWeightsExtra)
  36792. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36793. };
  36794. /**
  36795. * Serializes the VertexData
  36796. * @returns a serialized object
  36797. */
  36798. VertexData.prototype.serialize = function () {
  36799. var serializationObject = this.serialize();
  36800. if (this.positions) {
  36801. serializationObject.positions = this.positions;
  36802. }
  36803. if (this.normals) {
  36804. serializationObject.normals = this.normals;
  36805. }
  36806. if (this.tangents) {
  36807. serializationObject.tangents = this.tangents;
  36808. }
  36809. if (this.uvs) {
  36810. serializationObject.uvs = this.uvs;
  36811. }
  36812. if (this.uvs2) {
  36813. serializationObject.uvs2 = this.uvs2;
  36814. }
  36815. if (this.uvs3) {
  36816. serializationObject.uvs3 = this.uvs3;
  36817. }
  36818. if (this.uvs4) {
  36819. serializationObject.uvs4 = this.uvs4;
  36820. }
  36821. if (this.uvs5) {
  36822. serializationObject.uvs5 = this.uvs5;
  36823. }
  36824. if (this.uvs6) {
  36825. serializationObject.uvs6 = this.uvs6;
  36826. }
  36827. if (this.colors) {
  36828. serializationObject.colors = this.colors;
  36829. }
  36830. if (this.matricesIndices) {
  36831. serializationObject.matricesIndices = this.matricesIndices;
  36832. serializationObject.matricesIndices._isExpanded = true;
  36833. }
  36834. if (this.matricesWeights) {
  36835. serializationObject.matricesWeights = this.matricesWeights;
  36836. }
  36837. if (this.matricesIndicesExtra) {
  36838. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36839. serializationObject.matricesIndicesExtra._isExpanded = true;
  36840. }
  36841. if (this.matricesWeightsExtra) {
  36842. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36843. }
  36844. serializationObject.indices = this.indices;
  36845. return serializationObject;
  36846. };
  36847. // Statics
  36848. /**
  36849. * Extracts the vertexData from a mesh
  36850. * @param mesh the mesh from which to extract the VertexData
  36851. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36852. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36853. * @returns the object VertexData associated to the passed mesh
  36854. */
  36855. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36856. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36857. };
  36858. /**
  36859. * Extracts the vertexData from the geometry
  36860. * @param geometry the geometry from which to extract the VertexData
  36861. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36862. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36863. * @returns the object VertexData associated to the passed mesh
  36864. */
  36865. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36866. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36867. };
  36868. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36869. var result = new VertexData();
  36870. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36871. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36872. }
  36873. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36874. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36875. }
  36876. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36877. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36878. }
  36879. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36880. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36881. }
  36882. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36883. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36884. }
  36885. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36886. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36887. }
  36888. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36889. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36890. }
  36891. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36892. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36893. }
  36894. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36895. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36896. }
  36897. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36898. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36899. }
  36900. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36901. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36902. }
  36903. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36904. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36905. }
  36906. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36907. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36908. }
  36909. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36910. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36911. }
  36912. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36913. return result;
  36914. };
  36915. /**
  36916. * Creates the VertexData for a Ribbon
  36917. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36918. * * pathArray array of paths, each of which an array of successive Vector3
  36919. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36920. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36921. * * 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
  36922. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36923. * * 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)
  36924. * * 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)
  36925. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36926. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36927. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36928. * @returns the VertexData of the ribbon
  36929. */
  36930. VertexData.CreateRibbon = function (options) {
  36931. var pathArray = options.pathArray;
  36932. var closeArray = options.closeArray || false;
  36933. var closePath = options.closePath || false;
  36934. var invertUV = options.invertUV || false;
  36935. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36936. var offset = options.offset || defaultOffset;
  36937. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36938. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36939. var customUV = options.uvs;
  36940. var customColors = options.colors;
  36941. var positions = [];
  36942. var indices = [];
  36943. var normals = [];
  36944. var uvs = [];
  36945. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36946. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36947. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36948. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36949. var minlg; // minimal length among all paths from pathArray
  36950. var lg = []; // array of path lengths : nb of vertex per path
  36951. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36952. var p; // path iterator
  36953. var i; // point iterator
  36954. var j; // point iterator
  36955. // if single path in pathArray
  36956. if (pathArray.length < 2) {
  36957. var ar1 = [];
  36958. var ar2 = [];
  36959. for (i = 0; i < pathArray[0].length - offset; i++) {
  36960. ar1.push(pathArray[0][i]);
  36961. ar2.push(pathArray[0][i + offset]);
  36962. }
  36963. pathArray = [ar1, ar2];
  36964. }
  36965. // positions and horizontal distances (u)
  36966. var idc = 0;
  36967. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36968. var path;
  36969. var l;
  36970. minlg = pathArray[0].length;
  36971. var vectlg;
  36972. var dist;
  36973. for (p = 0; p < pathArray.length; p++) {
  36974. uTotalDistance[p] = 0;
  36975. us[p] = [0];
  36976. path = pathArray[p];
  36977. l = path.length;
  36978. minlg = (minlg < l) ? minlg : l;
  36979. j = 0;
  36980. while (j < l) {
  36981. positions.push(path[j].x, path[j].y, path[j].z);
  36982. if (j > 0) {
  36983. vectlg = path[j].subtract(path[j - 1]).length();
  36984. dist = vectlg + uTotalDistance[p];
  36985. us[p].push(dist);
  36986. uTotalDistance[p] = dist;
  36987. }
  36988. j++;
  36989. }
  36990. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36991. j--;
  36992. positions.push(path[0].x, path[0].y, path[0].z);
  36993. vectlg = path[j].subtract(path[0]).length();
  36994. dist = vectlg + uTotalDistance[p];
  36995. us[p].push(dist);
  36996. uTotalDistance[p] = dist;
  36997. }
  36998. lg[p] = l + closePathCorr;
  36999. idx[p] = idc;
  37000. idc += (l + closePathCorr);
  37001. }
  37002. // vertical distances (v)
  37003. var path1;
  37004. var path2;
  37005. var vertex1 = null;
  37006. var vertex2 = null;
  37007. for (i = 0; i < minlg + closePathCorr; i++) {
  37008. vTotalDistance[i] = 0;
  37009. vs[i] = [0];
  37010. for (p = 0; p < pathArray.length - 1; p++) {
  37011. path1 = pathArray[p];
  37012. path2 = pathArray[p + 1];
  37013. if (i === minlg) { // closePath
  37014. vertex1 = path1[0];
  37015. vertex2 = path2[0];
  37016. }
  37017. else {
  37018. vertex1 = path1[i];
  37019. vertex2 = path2[i];
  37020. }
  37021. vectlg = vertex2.subtract(vertex1).length();
  37022. dist = vectlg + vTotalDistance[i];
  37023. vs[i].push(dist);
  37024. vTotalDistance[i] = dist;
  37025. }
  37026. if (closeArray && vertex2 && vertex1) {
  37027. path1 = pathArray[p];
  37028. path2 = pathArray[0];
  37029. if (i === minlg) { // closePath
  37030. vertex2 = path2[0];
  37031. }
  37032. vectlg = vertex2.subtract(vertex1).length();
  37033. dist = vectlg + vTotalDistance[i];
  37034. vTotalDistance[i] = dist;
  37035. }
  37036. }
  37037. // uvs
  37038. var u;
  37039. var v;
  37040. if (customUV) {
  37041. for (p = 0; p < customUV.length; p++) {
  37042. uvs.push(customUV[p].x, customUV[p].y);
  37043. }
  37044. }
  37045. else {
  37046. for (p = 0; p < pathArray.length; p++) {
  37047. for (i = 0; i < minlg + closePathCorr; i++) {
  37048. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37049. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37050. if (invertUV) {
  37051. uvs.push(v, u);
  37052. }
  37053. else {
  37054. uvs.push(u, v);
  37055. }
  37056. }
  37057. }
  37058. }
  37059. // indices
  37060. p = 0; // path index
  37061. var pi = 0; // positions array index
  37062. var l1 = lg[p] - 1; // path1 length
  37063. var l2 = lg[p + 1] - 1; // path2 length
  37064. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37065. var shft = idx[1] - idx[0]; // shift
  37066. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37067. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37068. // 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
  37069. indices.push(pi, pi + shft, pi + 1);
  37070. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37071. pi += 1;
  37072. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37073. p++;
  37074. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37075. shft = idx[0] - idx[p];
  37076. l1 = lg[p] - 1;
  37077. l2 = lg[0] - 1;
  37078. }
  37079. else {
  37080. shft = idx[p + 1] - idx[p];
  37081. l1 = lg[p] - 1;
  37082. l2 = lg[p + 1] - 1;
  37083. }
  37084. pi = idx[p];
  37085. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37086. }
  37087. }
  37088. // normals
  37089. VertexData.ComputeNormals(positions, indices, normals);
  37090. if (closePath) { // update both the first and last vertex normals to their average value
  37091. var indexFirst = 0;
  37092. var indexLast = 0;
  37093. for (p = 0; p < pathArray.length; p++) {
  37094. indexFirst = idx[p] * 3;
  37095. if (p + 1 < pathArray.length) {
  37096. indexLast = (idx[p + 1] - 1) * 3;
  37097. }
  37098. else {
  37099. indexLast = normals.length - 3;
  37100. }
  37101. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37102. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37103. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37104. normals[indexLast] = normals[indexFirst];
  37105. normals[indexLast + 1] = normals[indexFirst + 1];
  37106. normals[indexLast + 2] = normals[indexFirst + 2];
  37107. }
  37108. }
  37109. // sides
  37110. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37111. // Colors
  37112. var colors = null;
  37113. if (customColors) {
  37114. colors = new Float32Array(customColors.length * 4);
  37115. for (var c = 0; c < customColors.length; c++) {
  37116. colors[c * 4] = customColors[c].r;
  37117. colors[c * 4 + 1] = customColors[c].g;
  37118. colors[c * 4 + 2] = customColors[c].b;
  37119. colors[c * 4 + 3] = customColors[c].a;
  37120. }
  37121. }
  37122. // Result
  37123. var vertexData = new VertexData();
  37124. var positions32 = new Float32Array(positions);
  37125. var normals32 = new Float32Array(normals);
  37126. var uvs32 = new Float32Array(uvs);
  37127. vertexData.indices = indices;
  37128. vertexData.positions = positions32;
  37129. vertexData.normals = normals32;
  37130. vertexData.uvs = uvs32;
  37131. if (colors) {
  37132. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37133. }
  37134. if (closePath) {
  37135. vertexData._idx = idx;
  37136. }
  37137. return vertexData;
  37138. };
  37139. /**
  37140. * Creates the VertexData for a box
  37141. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37142. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37143. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37144. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37145. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37146. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37147. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37148. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37149. * * 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)
  37150. * * 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)
  37151. * @returns the VertexData of the box
  37152. */
  37153. VertexData.CreateBox = function (options) {
  37154. var normalsSource = [
  37155. new BABYLON.Vector3(0, 0, 1),
  37156. new BABYLON.Vector3(0, 0, -1),
  37157. new BABYLON.Vector3(1, 0, 0),
  37158. new BABYLON.Vector3(-1, 0, 0),
  37159. new BABYLON.Vector3(0, 1, 0),
  37160. new BABYLON.Vector3(0, -1, 0)
  37161. ];
  37162. var indices = [];
  37163. var positions = [];
  37164. var normals = [];
  37165. var uvs = [];
  37166. var width = options.width || options.size || 1;
  37167. var height = options.height || options.size || 1;
  37168. var depth = options.depth || options.size || 1;
  37169. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37170. var faceUV = options.faceUV || new Array(6);
  37171. var faceColors = options.faceColors;
  37172. var colors = [];
  37173. // default face colors and UV if undefined
  37174. for (var f = 0; f < 6; f++) {
  37175. if (faceUV[f] === undefined) {
  37176. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37177. }
  37178. if (faceColors && faceColors[f] === undefined) {
  37179. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37180. }
  37181. }
  37182. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37183. // Create each face in turn.
  37184. for (var index = 0; index < normalsSource.length; index++) {
  37185. var normal = normalsSource[index];
  37186. // Get two vectors perpendicular to the face normal and to each other.
  37187. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37188. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37189. // Six indices (two triangles) per face.
  37190. var verticesLength = positions.length / 3;
  37191. indices.push(verticesLength);
  37192. indices.push(verticesLength + 1);
  37193. indices.push(verticesLength + 2);
  37194. indices.push(verticesLength);
  37195. indices.push(verticesLength + 2);
  37196. indices.push(verticesLength + 3);
  37197. // Four vertices per face.
  37198. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37199. positions.push(vertex.x, vertex.y, vertex.z);
  37200. normals.push(normal.x, normal.y, normal.z);
  37201. uvs.push(faceUV[index].z, faceUV[index].w);
  37202. if (faceColors) {
  37203. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37204. }
  37205. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37206. positions.push(vertex.x, vertex.y, vertex.z);
  37207. normals.push(normal.x, normal.y, normal.z);
  37208. uvs.push(faceUV[index].x, faceUV[index].w);
  37209. if (faceColors) {
  37210. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37211. }
  37212. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37213. positions.push(vertex.x, vertex.y, vertex.z);
  37214. normals.push(normal.x, normal.y, normal.z);
  37215. uvs.push(faceUV[index].x, faceUV[index].y);
  37216. if (faceColors) {
  37217. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37218. }
  37219. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37220. positions.push(vertex.x, vertex.y, vertex.z);
  37221. normals.push(normal.x, normal.y, normal.z);
  37222. uvs.push(faceUV[index].z, faceUV[index].y);
  37223. if (faceColors) {
  37224. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37225. }
  37226. }
  37227. // sides
  37228. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37229. // Result
  37230. var vertexData = new VertexData();
  37231. vertexData.indices = indices;
  37232. vertexData.positions = positions;
  37233. vertexData.normals = normals;
  37234. vertexData.uvs = uvs;
  37235. if (faceColors) {
  37236. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37237. vertexData.colors = totalColors;
  37238. }
  37239. return vertexData;
  37240. };
  37241. /**
  37242. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37243. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37244. * * segments sets the number of horizontal strips optional, default 32
  37245. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37246. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37247. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37248. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37249. * * 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
  37250. * * 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
  37251. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37252. * * 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)
  37253. * * 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)
  37254. * @returns the VertexData of the ellipsoid
  37255. */
  37256. VertexData.CreateSphere = function (options) {
  37257. var segments = options.segments || 32;
  37258. var diameterX = options.diameterX || options.diameter || 1;
  37259. var diameterY = options.diameterY || options.diameter || 1;
  37260. var diameterZ = options.diameterZ || options.diameter || 1;
  37261. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37262. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37263. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37264. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37265. var totalZRotationSteps = 2 + segments;
  37266. var totalYRotationSteps = 2 * totalZRotationSteps;
  37267. var indices = [];
  37268. var positions = [];
  37269. var normals = [];
  37270. var uvs = [];
  37271. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37272. var normalizedZ = zRotationStep / totalZRotationSteps;
  37273. var angleZ = normalizedZ * Math.PI * slice;
  37274. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37275. var normalizedY = yRotationStep / totalYRotationSteps;
  37276. var angleY = normalizedY * Math.PI * 2 * arc;
  37277. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37278. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37279. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37280. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37281. var vertex = complete.multiply(radius);
  37282. var normal = complete.divide(radius).normalize();
  37283. positions.push(vertex.x, vertex.y, vertex.z);
  37284. normals.push(normal.x, normal.y, normal.z);
  37285. uvs.push(normalizedY, normalizedZ);
  37286. }
  37287. if (zRotationStep > 0) {
  37288. var verticesCount = positions.length / 3;
  37289. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37290. indices.push((firstIndex));
  37291. indices.push((firstIndex + 1));
  37292. indices.push(firstIndex + totalYRotationSteps + 1);
  37293. indices.push((firstIndex + totalYRotationSteps + 1));
  37294. indices.push((firstIndex + 1));
  37295. indices.push((firstIndex + totalYRotationSteps + 2));
  37296. }
  37297. }
  37298. }
  37299. // Sides
  37300. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37301. // Result
  37302. var vertexData = new VertexData();
  37303. vertexData.indices = indices;
  37304. vertexData.positions = positions;
  37305. vertexData.normals = normals;
  37306. vertexData.uvs = uvs;
  37307. return vertexData;
  37308. };
  37309. /**
  37310. * Creates the VertexData for a cylinder, cone or prism
  37311. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37312. * * height sets the height (y direction) of the cylinder, optional, default 2
  37313. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37314. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37315. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37316. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37317. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37318. * * 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
  37319. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37320. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37321. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37322. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37323. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37324. * * 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)
  37325. * * 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)
  37326. * @returns the VertexData of the cylinder, cone or prism
  37327. */
  37328. VertexData.CreateCylinder = function (options) {
  37329. var height = options.height || 2;
  37330. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37331. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37332. var tessellation = options.tessellation || 24;
  37333. var subdivisions = options.subdivisions || 1;
  37334. var hasRings = options.hasRings ? true : false;
  37335. var enclose = options.enclose ? true : false;
  37336. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37337. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37338. var faceUV = options.faceUV || new Array(3);
  37339. var faceColors = options.faceColors;
  37340. // default face colors and UV if undefined
  37341. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37342. var ringNb = (hasRings) ? subdivisions : 1;
  37343. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37344. var f;
  37345. for (f = 0; f < surfaceNb; f++) {
  37346. if (faceColors && faceColors[f] === undefined) {
  37347. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37348. }
  37349. }
  37350. for (f = 0; f < surfaceNb; f++) {
  37351. if (faceUV && faceUV[f] === undefined) {
  37352. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37353. }
  37354. }
  37355. var indices = new Array();
  37356. var positions = new Array();
  37357. var normals = new Array();
  37358. var uvs = new Array();
  37359. var colors = new Array();
  37360. var angle_step = Math.PI * 2 * arc / tessellation;
  37361. var angle;
  37362. var h;
  37363. var radius;
  37364. var tan = (diameterBottom - diameterTop) / 2 / height;
  37365. var ringVertex = BABYLON.Vector3.Zero();
  37366. var ringNormal = BABYLON.Vector3.Zero();
  37367. var ringFirstVertex = BABYLON.Vector3.Zero();
  37368. var ringFirstNormal = BABYLON.Vector3.Zero();
  37369. var quadNormal = BABYLON.Vector3.Zero();
  37370. var Y = BABYLON.Axis.Y;
  37371. // positions, normals, uvs
  37372. var i;
  37373. var j;
  37374. var r;
  37375. var ringIdx = 1;
  37376. var s = 1; // surface index
  37377. var cs = 0;
  37378. var v = 0;
  37379. for (i = 0; i <= subdivisions; i++) {
  37380. h = i / subdivisions;
  37381. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37382. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37383. for (r = 0; r < ringIdx; r++) {
  37384. if (hasRings) {
  37385. s += r;
  37386. }
  37387. if (enclose) {
  37388. s += 2 * r;
  37389. }
  37390. for (j = 0; j <= tessellation; j++) {
  37391. angle = j * angle_step;
  37392. // position
  37393. ringVertex.x = Math.cos(-angle) * radius;
  37394. ringVertex.y = -height / 2 + h * height;
  37395. ringVertex.z = Math.sin(-angle) * radius;
  37396. // normal
  37397. if (diameterTop === 0 && i === subdivisions) {
  37398. // if no top cap, reuse former normals
  37399. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37400. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37401. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37402. }
  37403. else {
  37404. ringNormal.x = ringVertex.x;
  37405. ringNormal.z = ringVertex.z;
  37406. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37407. ringNormal.normalize();
  37408. }
  37409. // keep first ring vertex values for enclose
  37410. if (j === 0) {
  37411. ringFirstVertex.copyFrom(ringVertex);
  37412. ringFirstNormal.copyFrom(ringNormal);
  37413. }
  37414. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37415. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37416. if (hasRings) {
  37417. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37418. }
  37419. else {
  37420. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37421. }
  37422. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37423. if (faceColors) {
  37424. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37425. }
  37426. }
  37427. // if enclose, add four vertices and their dedicated normals
  37428. if (arc !== 1 && enclose) {
  37429. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37430. positions.push(0, ringVertex.y, 0);
  37431. positions.push(0, ringVertex.y, 0);
  37432. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37433. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37434. quadNormal.normalize();
  37435. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37436. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37437. quadNormal.normalize();
  37438. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37439. if (hasRings) {
  37440. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37441. }
  37442. else {
  37443. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37444. }
  37445. uvs.push(faceUV[s + 1].x, v);
  37446. uvs.push(faceUV[s + 1].z, v);
  37447. if (hasRings) {
  37448. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37449. }
  37450. else {
  37451. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37452. }
  37453. uvs.push(faceUV[s + 2].x, v);
  37454. uvs.push(faceUV[s + 2].z, v);
  37455. if (faceColors) {
  37456. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37457. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37458. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37459. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37460. }
  37461. }
  37462. if (cs !== s) {
  37463. cs = s;
  37464. }
  37465. }
  37466. }
  37467. // indices
  37468. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37469. var s;
  37470. i = 0;
  37471. for (s = 0; s < subdivisions; s++) {
  37472. var i0 = 0;
  37473. var i1 = 0;
  37474. var i2 = 0;
  37475. var i3 = 0;
  37476. for (j = 0; j < tessellation; j++) {
  37477. i0 = i * (e + 1) + j;
  37478. i1 = (i + 1) * (e + 1) + j;
  37479. i2 = i * (e + 1) + (j + 1);
  37480. i3 = (i + 1) * (e + 1) + (j + 1);
  37481. indices.push(i0, i1, i2);
  37482. indices.push(i3, i2, i1);
  37483. }
  37484. if (arc !== 1 && enclose) { // if enclose, add two quads
  37485. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37486. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37487. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37488. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37489. }
  37490. i = (hasRings) ? (i + 2) : (i + 1);
  37491. }
  37492. // Caps
  37493. var createCylinderCap = function (isTop) {
  37494. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37495. if (radius === 0) {
  37496. return;
  37497. }
  37498. // Cap positions, normals & uvs
  37499. var angle;
  37500. var circleVector;
  37501. var i;
  37502. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37503. var c = null;
  37504. if (faceColors) {
  37505. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37506. }
  37507. // cap center
  37508. var vbase = positions.length / 3;
  37509. var offset = isTop ? height / 2 : -height / 2;
  37510. var center = new BABYLON.Vector3(0, offset, 0);
  37511. positions.push(center.x, center.y, center.z);
  37512. normals.push(0, isTop ? 1 : -1, 0);
  37513. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37514. if (c) {
  37515. colors.push(c.r, c.g, c.b, c.a);
  37516. }
  37517. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37518. for (i = 0; i <= tessellation; i++) {
  37519. angle = Math.PI * 2 * i * arc / tessellation;
  37520. var cos = Math.cos(-angle);
  37521. var sin = Math.sin(-angle);
  37522. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37523. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37524. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37525. normals.push(0, isTop ? 1 : -1, 0);
  37526. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37527. if (c) {
  37528. colors.push(c.r, c.g, c.b, c.a);
  37529. }
  37530. }
  37531. // Cap indices
  37532. for (i = 0; i < tessellation; i++) {
  37533. if (!isTop) {
  37534. indices.push(vbase);
  37535. indices.push(vbase + (i + 1));
  37536. indices.push(vbase + (i + 2));
  37537. }
  37538. else {
  37539. indices.push(vbase);
  37540. indices.push(vbase + (i + 2));
  37541. indices.push(vbase + (i + 1));
  37542. }
  37543. }
  37544. };
  37545. // add caps to geometry
  37546. createCylinderCap(false);
  37547. createCylinderCap(true);
  37548. // Sides
  37549. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37550. var vertexData = new VertexData();
  37551. vertexData.indices = indices;
  37552. vertexData.positions = positions;
  37553. vertexData.normals = normals;
  37554. vertexData.uvs = uvs;
  37555. if (faceColors) {
  37556. vertexData.colors = colors;
  37557. }
  37558. return vertexData;
  37559. };
  37560. /**
  37561. * Creates the VertexData for a torus
  37562. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37563. * * diameter the diameter of the torus, optional default 1
  37564. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37565. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37566. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37567. * * 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)
  37568. * * 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)
  37569. * @returns the VertexData of the torus
  37570. */
  37571. VertexData.CreateTorus = function (options) {
  37572. var indices = [];
  37573. var positions = [];
  37574. var normals = [];
  37575. var uvs = [];
  37576. var diameter = options.diameter || 1;
  37577. var thickness = options.thickness || 0.5;
  37578. var tessellation = options.tessellation || 16;
  37579. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37580. var stride = tessellation + 1;
  37581. for (var i = 0; i <= tessellation; i++) {
  37582. var u = i / tessellation;
  37583. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37584. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37585. for (var j = 0; j <= tessellation; j++) {
  37586. var v = 1 - j / tessellation;
  37587. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37588. var dx = Math.cos(innerAngle);
  37589. var dy = Math.sin(innerAngle);
  37590. // Create a vertex.
  37591. var normal = new BABYLON.Vector3(dx, dy, 0);
  37592. var position = normal.scale(thickness / 2);
  37593. var textureCoordinate = new BABYLON.Vector2(u, v);
  37594. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37595. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37596. positions.push(position.x, position.y, position.z);
  37597. normals.push(normal.x, normal.y, normal.z);
  37598. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37599. // And create indices for two triangles.
  37600. var nextI = (i + 1) % stride;
  37601. var nextJ = (j + 1) % stride;
  37602. indices.push(i * stride + j);
  37603. indices.push(i * stride + nextJ);
  37604. indices.push(nextI * stride + j);
  37605. indices.push(i * stride + nextJ);
  37606. indices.push(nextI * stride + nextJ);
  37607. indices.push(nextI * stride + j);
  37608. }
  37609. }
  37610. // Sides
  37611. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37612. // Result
  37613. var vertexData = new VertexData();
  37614. vertexData.indices = indices;
  37615. vertexData.positions = positions;
  37616. vertexData.normals = normals;
  37617. vertexData.uvs = uvs;
  37618. return vertexData;
  37619. };
  37620. /**
  37621. * Creates the VertexData of the LineSystem
  37622. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37623. * - lines an array of lines, each line being an array of successive Vector3
  37624. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37625. * @returns the VertexData of the LineSystem
  37626. */
  37627. VertexData.CreateLineSystem = function (options) {
  37628. var indices = [];
  37629. var positions = [];
  37630. var lines = options.lines;
  37631. var colors = options.colors;
  37632. var vertexColors = [];
  37633. var idx = 0;
  37634. for (var l = 0; l < lines.length; l++) {
  37635. var points = lines[l];
  37636. for (var index = 0; index < points.length; index++) {
  37637. positions.push(points[index].x, points[index].y, points[index].z);
  37638. if (colors) {
  37639. var color = colors[l];
  37640. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37641. }
  37642. if (index > 0) {
  37643. indices.push(idx - 1);
  37644. indices.push(idx);
  37645. }
  37646. idx++;
  37647. }
  37648. }
  37649. var vertexData = new VertexData();
  37650. vertexData.indices = indices;
  37651. vertexData.positions = positions;
  37652. if (colors) {
  37653. vertexData.colors = vertexColors;
  37654. }
  37655. return vertexData;
  37656. };
  37657. /**
  37658. * Create the VertexData for a DashedLines
  37659. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37660. * - points an array successive Vector3
  37661. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37662. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37663. * - dashNb the intended total number of dashes, optional, default 200
  37664. * @returns the VertexData for the DashedLines
  37665. */
  37666. VertexData.CreateDashedLines = function (options) {
  37667. var dashSize = options.dashSize || 3;
  37668. var gapSize = options.gapSize || 1;
  37669. var dashNb = options.dashNb || 200;
  37670. var points = options.points;
  37671. var positions = new Array();
  37672. var indices = new Array();
  37673. var curvect = BABYLON.Vector3.Zero();
  37674. var lg = 0;
  37675. var nb = 0;
  37676. var shft = 0;
  37677. var dashshft = 0;
  37678. var curshft = 0;
  37679. var idx = 0;
  37680. var i = 0;
  37681. for (i = 0; i < points.length - 1; i++) {
  37682. points[i + 1].subtractToRef(points[i], curvect);
  37683. lg += curvect.length();
  37684. }
  37685. shft = lg / dashNb;
  37686. dashshft = dashSize * shft / (dashSize + gapSize);
  37687. for (i = 0; i < points.length - 1; i++) {
  37688. points[i + 1].subtractToRef(points[i], curvect);
  37689. nb = Math.floor(curvect.length() / shft);
  37690. curvect.normalize();
  37691. for (var j = 0; j < nb; j++) {
  37692. curshft = shft * j;
  37693. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37694. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37695. indices.push(idx, idx + 1);
  37696. idx += 2;
  37697. }
  37698. }
  37699. // Result
  37700. var vertexData = new VertexData();
  37701. vertexData.positions = positions;
  37702. vertexData.indices = indices;
  37703. return vertexData;
  37704. };
  37705. /**
  37706. * Creates the VertexData for a Ground
  37707. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37708. * - width the width (x direction) of the ground, optional, default 1
  37709. * - height the height (z direction) of the ground, optional, default 1
  37710. * - subdivisions the number of subdivisions per side, optional, default 1
  37711. * @returns the VertexData of the Ground
  37712. */
  37713. VertexData.CreateGround = function (options) {
  37714. var indices = [];
  37715. var positions = [];
  37716. var normals = [];
  37717. var uvs = [];
  37718. var row, col;
  37719. var width = options.width || 1;
  37720. var height = options.height || 1;
  37721. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37722. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37723. for (row = 0; row <= subdivisionsY; row++) {
  37724. for (col = 0; col <= subdivisionsX; col++) {
  37725. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37726. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37727. positions.push(position.x, position.y, position.z);
  37728. normals.push(normal.x, normal.y, normal.z);
  37729. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37730. }
  37731. }
  37732. for (row = 0; row < subdivisionsY; row++) {
  37733. for (col = 0; col < subdivisionsX; col++) {
  37734. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37735. indices.push(col + 1 + row * (subdivisionsX + 1));
  37736. indices.push(col + row * (subdivisionsX + 1));
  37737. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37738. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37739. indices.push(col + row * (subdivisionsX + 1));
  37740. }
  37741. }
  37742. // Result
  37743. var vertexData = new VertexData();
  37744. vertexData.indices = indices;
  37745. vertexData.positions = positions;
  37746. vertexData.normals = normals;
  37747. vertexData.uvs = uvs;
  37748. return vertexData;
  37749. };
  37750. /**
  37751. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37752. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37753. * * xmin the ground minimum X coordinate, optional, default -1
  37754. * * zmin the ground minimum Z coordinate, optional, default -1
  37755. * * xmax the ground maximum X coordinate, optional, default 1
  37756. * * zmax the ground maximum Z coordinate, optional, default 1
  37757. * * 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}
  37758. * * 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}
  37759. * @returns the VertexData of the TiledGround
  37760. */
  37761. VertexData.CreateTiledGround = function (options) {
  37762. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37763. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37764. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37765. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37766. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37767. var precision = options.precision || { w: 1, h: 1 };
  37768. var indices = new Array();
  37769. var positions = new Array();
  37770. var normals = new Array();
  37771. var uvs = new Array();
  37772. var row, col, tileRow, tileCol;
  37773. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37774. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37775. precision.w = (precision.w < 1) ? 1 : precision.w;
  37776. precision.h = (precision.h < 1) ? 1 : precision.h;
  37777. var tileSize = {
  37778. 'w': (xmax - xmin) / subdivisions.w,
  37779. 'h': (zmax - zmin) / subdivisions.h
  37780. };
  37781. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37782. // Indices
  37783. var base = positions.length / 3;
  37784. var rowLength = precision.w + 1;
  37785. for (row = 0; row < precision.h; row++) {
  37786. for (col = 0; col < precision.w; col++) {
  37787. var square = [
  37788. base + col + row * rowLength,
  37789. base + (col + 1) + row * rowLength,
  37790. base + (col + 1) + (row + 1) * rowLength,
  37791. base + col + (row + 1) * rowLength
  37792. ];
  37793. indices.push(square[1]);
  37794. indices.push(square[2]);
  37795. indices.push(square[3]);
  37796. indices.push(square[0]);
  37797. indices.push(square[1]);
  37798. indices.push(square[3]);
  37799. }
  37800. }
  37801. // Position, normals and uvs
  37802. var position = BABYLON.Vector3.Zero();
  37803. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37804. for (row = 0; row <= precision.h; row++) {
  37805. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37806. for (col = 0; col <= precision.w; col++) {
  37807. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37808. position.y = 0;
  37809. positions.push(position.x, position.y, position.z);
  37810. normals.push(normal.x, normal.y, normal.z);
  37811. uvs.push(col / precision.w, row / precision.h);
  37812. }
  37813. }
  37814. }
  37815. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37816. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37817. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37818. }
  37819. }
  37820. // Result
  37821. var vertexData = new VertexData();
  37822. vertexData.indices = indices;
  37823. vertexData.positions = positions;
  37824. vertexData.normals = normals;
  37825. vertexData.uvs = uvs;
  37826. return vertexData;
  37827. };
  37828. /**
  37829. * Creates the VertexData of the Ground designed from a heightmap
  37830. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37831. * * width the width (x direction) of the ground
  37832. * * height the height (z direction) of the ground
  37833. * * subdivisions the number of subdivisions per side
  37834. * * minHeight the minimum altitude on the ground, optional, default 0
  37835. * * maxHeight the maximum altitude on the ground, optional default 1
  37836. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37837. * * buffer the array holding the image color data
  37838. * * bufferWidth the width of image
  37839. * * bufferHeight the height of image
  37840. * @returns the VertexData of the Ground designed from a heightmap
  37841. */
  37842. VertexData.CreateGroundFromHeightMap = function (options) {
  37843. var indices = [];
  37844. var positions = [];
  37845. var normals = [];
  37846. var uvs = [];
  37847. var row, col;
  37848. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37849. // Vertices
  37850. for (row = 0; row <= options.subdivisions; row++) {
  37851. for (col = 0; col <= options.subdivisions; col++) {
  37852. 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));
  37853. // Compute height
  37854. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37855. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37856. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37857. var r = options.buffer[pos] / 255.0;
  37858. var g = options.buffer[pos + 1] / 255.0;
  37859. var b = options.buffer[pos + 2] / 255.0;
  37860. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37861. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37862. // Add vertex
  37863. positions.push(position.x, position.y, position.z);
  37864. normals.push(0, 0, 0);
  37865. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37866. }
  37867. }
  37868. // Indices
  37869. for (row = 0; row < options.subdivisions; row++) {
  37870. for (col = 0; col < options.subdivisions; col++) {
  37871. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37872. indices.push(col + 1 + row * (options.subdivisions + 1));
  37873. indices.push(col + row * (options.subdivisions + 1));
  37874. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37875. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37876. indices.push(col + row * (options.subdivisions + 1));
  37877. }
  37878. }
  37879. // Normals
  37880. VertexData.ComputeNormals(positions, indices, normals);
  37881. // Result
  37882. var vertexData = new VertexData();
  37883. vertexData.indices = indices;
  37884. vertexData.positions = positions;
  37885. vertexData.normals = normals;
  37886. vertexData.uvs = uvs;
  37887. return vertexData;
  37888. };
  37889. /**
  37890. * Creates the VertexData for a Plane
  37891. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37892. * * size sets the width and height of the plane to the value of size, optional default 1
  37893. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37894. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37895. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37896. * * 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)
  37897. * * 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)
  37898. * @returns the VertexData of the box
  37899. */
  37900. VertexData.CreatePlane = function (options) {
  37901. var indices = [];
  37902. var positions = [];
  37903. var normals = [];
  37904. var uvs = [];
  37905. var width = options.width || options.size || 1;
  37906. var height = options.height || options.size || 1;
  37907. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37908. // Vertices
  37909. var halfWidth = width / 2.0;
  37910. var halfHeight = height / 2.0;
  37911. positions.push(-halfWidth, -halfHeight, 0);
  37912. normals.push(0, 0, -1.0);
  37913. uvs.push(0.0, 0.0);
  37914. positions.push(halfWidth, -halfHeight, 0);
  37915. normals.push(0, 0, -1.0);
  37916. uvs.push(1.0, 0.0);
  37917. positions.push(halfWidth, halfHeight, 0);
  37918. normals.push(0, 0, -1.0);
  37919. uvs.push(1.0, 1.0);
  37920. positions.push(-halfWidth, halfHeight, 0);
  37921. normals.push(0, 0, -1.0);
  37922. uvs.push(0.0, 1.0);
  37923. // Indices
  37924. indices.push(0);
  37925. indices.push(1);
  37926. indices.push(2);
  37927. indices.push(0);
  37928. indices.push(2);
  37929. indices.push(3);
  37930. // Sides
  37931. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37932. // Result
  37933. var vertexData = new VertexData();
  37934. vertexData.indices = indices;
  37935. vertexData.positions = positions;
  37936. vertexData.normals = normals;
  37937. vertexData.uvs = uvs;
  37938. return vertexData;
  37939. };
  37940. /**
  37941. * Creates the VertexData of the Disc or regular Polygon
  37942. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37943. * * radius the radius of the disc, optional default 0.5
  37944. * * tessellation the number of polygon sides, optional, default 64
  37945. * * 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
  37946. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37947. * * 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)
  37948. * * 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)
  37949. * @returns the VertexData of the box
  37950. */
  37951. VertexData.CreateDisc = function (options) {
  37952. var positions = new Array();
  37953. var indices = new Array();
  37954. var normals = new Array();
  37955. var uvs = new Array();
  37956. var radius = options.radius || 0.5;
  37957. var tessellation = options.tessellation || 64;
  37958. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37960. // positions and uvs
  37961. positions.push(0, 0, 0); // disc center first
  37962. uvs.push(0.5, 0.5);
  37963. var theta = Math.PI * 2 * arc;
  37964. var step = theta / tessellation;
  37965. for (var a = 0; a < theta; a += step) {
  37966. var x = Math.cos(a);
  37967. var y = Math.sin(a);
  37968. var u = (x + 1) / 2;
  37969. var v = (1 - y) / 2;
  37970. positions.push(radius * x, radius * y, 0);
  37971. uvs.push(u, v);
  37972. }
  37973. if (arc === 1) {
  37974. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37975. uvs.push(uvs[2], uvs[3]);
  37976. }
  37977. //indices
  37978. var vertexNb = positions.length / 3;
  37979. for (var i = 1; i < vertexNb - 1; i++) {
  37980. indices.push(i + 1, 0, i);
  37981. }
  37982. // result
  37983. VertexData.ComputeNormals(positions, indices, normals);
  37984. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37985. var vertexData = new VertexData();
  37986. vertexData.indices = indices;
  37987. vertexData.positions = positions;
  37988. vertexData.normals = normals;
  37989. vertexData.uvs = uvs;
  37990. return vertexData;
  37991. };
  37992. /**
  37993. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37994. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37995. * @param polygon a mesh built from polygonTriangulation.build()
  37996. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37997. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37998. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37999. * @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)
  38000. * @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)
  38001. * @returns the VertexData of the Polygon
  38002. */
  38003. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38004. var faceUV = fUV || new Array(3);
  38005. var faceColors = fColors;
  38006. var colors = [];
  38007. // default face colors and UV if undefined
  38008. for (var f = 0; f < 3; f++) {
  38009. if (faceUV[f] === undefined) {
  38010. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38011. }
  38012. if (faceColors && faceColors[f] === undefined) {
  38013. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38014. }
  38015. }
  38016. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38017. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38018. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38019. var indices = polygon.getIndices();
  38020. // set face colours and textures
  38021. var idx = 0;
  38022. var face = 0;
  38023. for (var index = 0; index < normals.length; index += 3) {
  38024. //Edge Face no. 1
  38025. if (Math.abs(normals[index + 1]) < 0.001) {
  38026. face = 1;
  38027. }
  38028. //Top Face no. 0
  38029. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38030. face = 0;
  38031. }
  38032. //Bottom Face no. 2
  38033. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38034. face = 2;
  38035. }
  38036. idx = index / 3;
  38037. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38038. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38039. if (faceColors) {
  38040. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38041. }
  38042. }
  38043. // sides
  38044. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38045. // Result
  38046. var vertexData = new VertexData();
  38047. vertexData.indices = indices;
  38048. vertexData.positions = positions;
  38049. vertexData.normals = normals;
  38050. vertexData.uvs = uvs;
  38051. if (faceColors) {
  38052. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38053. vertexData.colors = totalColors;
  38054. }
  38055. return vertexData;
  38056. };
  38057. /**
  38058. * Creates the VertexData of the IcoSphere
  38059. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38060. * * radius the radius of the IcoSphere, optional default 1
  38061. * * radiusX allows stretching in the x direction, optional, default radius
  38062. * * radiusY allows stretching in the y direction, optional, default radius
  38063. * * radiusZ allows stretching in the z direction, optional, default radius
  38064. * * flat when true creates a flat shaded mesh, optional, default true
  38065. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38066. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38067. * * 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)
  38068. * * 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)
  38069. * @returns the VertexData of the IcoSphere
  38070. */
  38071. VertexData.CreateIcoSphere = function (options) {
  38072. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38073. var radius = options.radius || 1;
  38074. var flat = (options.flat === undefined) ? true : options.flat;
  38075. var subdivisions = options.subdivisions || 4;
  38076. var radiusX = options.radiusX || radius;
  38077. var radiusY = options.radiusY || radius;
  38078. var radiusZ = options.radiusZ || radius;
  38079. var t = (1 + Math.sqrt(5)) / 2;
  38080. // 12 vertex x,y,z
  38081. var ico_vertices = [
  38082. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38083. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38084. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38085. ];
  38086. // index of 3 vertex makes a face of icopshere
  38087. var ico_indices = [
  38088. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38089. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38090. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38091. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38092. ];
  38093. // vertex for uv have aliased position, not for UV
  38094. var vertices_unalias_id = [
  38095. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38096. // vertex alias
  38097. 0,
  38098. 2,
  38099. 3,
  38100. 3,
  38101. 3,
  38102. 4,
  38103. 7,
  38104. 8,
  38105. 9,
  38106. 9,
  38107. 10,
  38108. 11 // 23: B + 12
  38109. ];
  38110. // uv as integer step (not pixels !)
  38111. var ico_vertexuv = [
  38112. 5, 1, 3, 1, 6, 4, 0, 0,
  38113. 5, 3, 4, 2, 2, 2, 4, 0,
  38114. 2, 0, 1, 1, 6, 0, 6, 2,
  38115. // vertex alias (for same vertex on different faces)
  38116. 0, 4,
  38117. 3, 3,
  38118. 4, 4,
  38119. 3, 1,
  38120. 4, 2,
  38121. 4, 4,
  38122. 0, 2,
  38123. 1, 1,
  38124. 2, 2,
  38125. 3, 3,
  38126. 1, 3,
  38127. 2, 4 // 23: B + 12
  38128. ];
  38129. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38130. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38131. // First island of uv mapping
  38132. // v = 4h 3+ 2
  38133. // v = 3h 9+ 4
  38134. // v = 2h 9+ 5 B
  38135. // v = 1h 9 1 0
  38136. // v = 0h 3 8 7 A
  38137. // u = 0 1 2 3 4 5 6 *a
  38138. // Second island of uv mapping
  38139. // v = 4h 0+ B+ 4+
  38140. // v = 3h A+ 2+
  38141. // v = 2h 7+ 6 3+
  38142. // v = 1h 8+ 3+
  38143. // v = 0h
  38144. // u = 0 1 2 3 4 5 6 *a
  38145. // Face layout on texture UV mapping
  38146. // ============
  38147. // \ 4 /\ 16 / ======
  38148. // \ / \ / /\ 11 /
  38149. // \/ 7 \/ / \ /
  38150. // ======= / 10 \/
  38151. // /\ 17 /\ =======
  38152. // / \ / \ \ 15 /\
  38153. // / 8 \/ 12 \ \ / \
  38154. // ============ \/ 6 \
  38155. // \ 18 /\ ============
  38156. // \ / \ \ 5 /\ 0 /
  38157. // \/ 13 \ \ / \ /
  38158. // ======= \/ 1 \/
  38159. // =============
  38160. // /\ 19 /\ 2 /\
  38161. // / \ / \ / \
  38162. // / 14 \/ 9 \/ 3 \
  38163. // ===================
  38164. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38165. var ustep = 138 / 1024;
  38166. var vstep = 239 / 1024;
  38167. var uoffset = 60 / 1024;
  38168. var voffset = 26 / 1024;
  38169. // Second island should have margin, not to touch the first island
  38170. // avoid any borderline artefact in pixel rounding
  38171. var island_u_offset = -40 / 1024;
  38172. var island_v_offset = +20 / 1024;
  38173. // face is either island 0 or 1 :
  38174. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38175. var island = [
  38176. 0, 0, 0, 0, 1,
  38177. 0, 0, 1, 1, 0,
  38178. 0, 0, 1, 1, 0,
  38179. 0, 1, 1, 1, 0 // 15 - 19
  38180. ];
  38181. var indices = new Array();
  38182. var positions = new Array();
  38183. var normals = new Array();
  38184. var uvs = new Array();
  38185. var current_indice = 0;
  38186. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38187. var face_vertex_pos = new Array(3);
  38188. var face_vertex_uv = new Array(3);
  38189. var v012;
  38190. for (v012 = 0; v012 < 3; v012++) {
  38191. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38192. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38193. }
  38194. // create all with normals
  38195. for (var face = 0; face < 20; face++) {
  38196. // 3 vertex per face
  38197. for (v012 = 0; v012 < 3; v012++) {
  38198. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38199. var v_id = ico_indices[3 * face + v012];
  38200. // vertex have 3D position (x,y,z)
  38201. 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]);
  38202. // Normalize to get normal, then scale to radius
  38203. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38204. // uv Coordinates from vertex ID
  38205. 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);
  38206. }
  38207. // Subdivide the face (interpolate pos, norm, uv)
  38208. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38209. // - norm is linear interpolation of vertex corner normal
  38210. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38211. // - uv is linear interpolation
  38212. //
  38213. // Topology is as below for sub-divide by 2
  38214. // vertex shown as v0,v1,v2
  38215. // interp index is i1 to progress in range [v0,v1[
  38216. // interp index is i2 to progress in range [v0,v2[
  38217. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38218. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38219. //
  38220. //
  38221. // i2 v2
  38222. // ^ ^
  38223. // / / \
  38224. // / / \
  38225. // / / \
  38226. // / / (0,1) \
  38227. // / #---------\
  38228. // / / \ (0,0)'/ \
  38229. // / / \ / \
  38230. // / / \ / \
  38231. // / / (0,0) \ / (1,0) \
  38232. // / #---------#---------\
  38233. // v0 v1
  38234. //
  38235. // --------------------> i1
  38236. //
  38237. // interp of (i1,i2):
  38238. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38239. // along i1 : lerp(x0,x1, i1/(S-i2))
  38240. //
  38241. // centroid of triangle is needed to get help normal computation
  38242. // (c1,c2) are used for centroid location
  38243. var interp_vertex = function (i1, i2, c1, c2) {
  38244. // vertex is interpolated from
  38245. // - face_vertex_pos[0..2]
  38246. // - face_vertex_uv[0..2]
  38247. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38248. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38249. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38250. pos_interp.normalize();
  38251. var vertex_normal;
  38252. if (flat) {
  38253. // in flat mode, recalculate normal as face centroid normal
  38254. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38255. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38256. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38257. }
  38258. else {
  38259. // in smooth mode, recalculate normal from each single vertex position
  38260. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38261. }
  38262. // Vertex normal need correction due to X,Y,Z radius scaling
  38263. vertex_normal.x /= radiusX;
  38264. vertex_normal.y /= radiusY;
  38265. vertex_normal.z /= radiusZ;
  38266. vertex_normal.normalize();
  38267. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38268. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38269. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38270. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38271. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38272. uvs.push(uv_interp.x, uv_interp.y);
  38273. // push each vertex has member of a face
  38274. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38275. indices.push(current_indice);
  38276. current_indice++;
  38277. };
  38278. for (var i2 = 0; i2 < subdivisions; i2++) {
  38279. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38280. // face : (i1,i2) for /\ :
  38281. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38282. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38283. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38284. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38285. if (i1 + i2 + 1 < subdivisions) {
  38286. // face : (i1,i2)' for \/ :
  38287. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38288. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38289. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38290. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38291. }
  38292. }
  38293. }
  38294. }
  38295. // Sides
  38296. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38297. // Result
  38298. var vertexData = new VertexData();
  38299. vertexData.indices = indices;
  38300. vertexData.positions = positions;
  38301. vertexData.normals = normals;
  38302. vertexData.uvs = uvs;
  38303. return vertexData;
  38304. };
  38305. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38306. /**
  38307. * Creates the VertexData for a Polyhedron
  38308. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38309. * * type provided types are:
  38310. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38311. * * 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)
  38312. * * size the size of the IcoSphere, optional default 1
  38313. * * sizeX allows stretching in the x direction, optional, default size
  38314. * * sizeY allows stretching in the y direction, optional, default size
  38315. * * sizeZ allows stretching in the z direction, optional, default size
  38316. * * 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
  38317. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38318. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38319. * * flat when true creates a flat shaded mesh, optional, default true
  38320. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38321. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38322. * * 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)
  38323. * * 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)
  38324. * @returns the VertexData of the Polyhedron
  38325. */
  38326. VertexData.CreatePolyhedron = function (options) {
  38327. // provided polyhedron types :
  38328. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38329. // 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)
  38330. var polyhedra = [];
  38331. 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]] };
  38332. 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]] };
  38333. polyhedra[2] = {
  38334. 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]],
  38335. 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]]
  38336. };
  38337. polyhedra[3] = {
  38338. 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]],
  38339. 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]]
  38340. };
  38341. polyhedra[4] = {
  38342. 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]],
  38343. 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]]
  38344. };
  38345. 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]] };
  38346. 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]] };
  38347. 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]] };
  38348. 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]] };
  38349. 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]] };
  38350. 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]] };
  38351. 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]] };
  38352. 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]] };
  38353. 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]] };
  38354. polyhedra[14] = {
  38355. 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]],
  38356. 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]]
  38357. };
  38358. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38359. var size = options.size;
  38360. var sizeX = options.sizeX || size || 1;
  38361. var sizeY = options.sizeY || size || 1;
  38362. var sizeZ = options.sizeZ || size || 1;
  38363. var data = options.custom || polyhedra[type];
  38364. var nbfaces = data.face.length;
  38365. var faceUV = options.faceUV || new Array(nbfaces);
  38366. var faceColors = options.faceColors;
  38367. var flat = (options.flat === undefined) ? true : options.flat;
  38368. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38369. var positions = new Array();
  38370. var indices = new Array();
  38371. var normals = new Array();
  38372. var uvs = new Array();
  38373. var colors = new Array();
  38374. var index = 0;
  38375. var faceIdx = 0; // face cursor in the array "indexes"
  38376. var indexes = new Array();
  38377. var i = 0;
  38378. var f = 0;
  38379. var u, v, ang, x, y, tmp;
  38380. // default face colors and UV if undefined
  38381. if (flat) {
  38382. for (f = 0; f < nbfaces; f++) {
  38383. if (faceColors && faceColors[f] === undefined) {
  38384. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38385. }
  38386. if (faceUV && faceUV[f] === undefined) {
  38387. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38388. }
  38389. }
  38390. }
  38391. if (!flat) {
  38392. for (i = 0; i < data.vertex.length; i++) {
  38393. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38394. uvs.push(0, 0);
  38395. }
  38396. for (f = 0; f < nbfaces; f++) {
  38397. for (i = 0; i < data.face[f].length - 2; i++) {
  38398. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38399. }
  38400. }
  38401. }
  38402. else {
  38403. for (f = 0; f < nbfaces; f++) {
  38404. var fl = data.face[f].length; // number of vertices of the current face
  38405. ang = 2 * Math.PI / fl;
  38406. x = 0.5 * Math.tan(ang / 2);
  38407. y = 0.5;
  38408. // positions, uvs, colors
  38409. for (i = 0; i < fl; i++) {
  38410. // positions
  38411. 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);
  38412. indexes.push(index);
  38413. index++;
  38414. // uvs
  38415. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38416. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38417. uvs.push(u, v);
  38418. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38419. y = x * Math.sin(ang) + y * Math.cos(ang);
  38420. x = tmp;
  38421. // colors
  38422. if (faceColors) {
  38423. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38424. }
  38425. }
  38426. // indices from indexes
  38427. for (i = 0; i < fl - 2; i++) {
  38428. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38429. }
  38430. faceIdx += fl;
  38431. }
  38432. }
  38433. VertexData.ComputeNormals(positions, indices, normals);
  38434. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38435. var vertexData = new VertexData();
  38436. vertexData.positions = positions;
  38437. vertexData.indices = indices;
  38438. vertexData.normals = normals;
  38439. vertexData.uvs = uvs;
  38440. if (faceColors && flat) {
  38441. vertexData.colors = colors;
  38442. }
  38443. return vertexData;
  38444. };
  38445. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38446. /**
  38447. * Creates the VertexData for a TorusKnot
  38448. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38449. * * radius the radius of the torus knot, optional, default 2
  38450. * * tube the thickness of the tube, optional, default 0.5
  38451. * * radialSegments the number of sides on each tube segments, optional, default 32
  38452. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38453. * * p the number of windings around the z axis, optional, default 2
  38454. * * q the number of windings around the x axis, optional, default 3
  38455. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38456. * * 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)
  38457. * * 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)
  38458. * @returns the VertexData of the Torus Knot
  38459. */
  38460. VertexData.CreateTorusKnot = function (options) {
  38461. var indices = new Array();
  38462. var positions = new Array();
  38463. var normals = new Array();
  38464. var uvs = new Array();
  38465. var radius = options.radius || 2;
  38466. var tube = options.tube || 0.5;
  38467. var radialSegments = options.radialSegments || 32;
  38468. var tubularSegments = options.tubularSegments || 32;
  38469. var p = options.p || 2;
  38470. var q = options.q || 3;
  38471. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38472. // Helper
  38473. var getPos = function (angle) {
  38474. var cu = Math.cos(angle);
  38475. var su = Math.sin(angle);
  38476. var quOverP = q / p * angle;
  38477. var cs = Math.cos(quOverP);
  38478. var tx = radius * (2 + cs) * 0.5 * cu;
  38479. var ty = radius * (2 + cs) * su * 0.5;
  38480. var tz = radius * Math.sin(quOverP) * 0.5;
  38481. return new BABYLON.Vector3(tx, ty, tz);
  38482. };
  38483. // Vertices
  38484. var i;
  38485. var j;
  38486. for (i = 0; i <= radialSegments; i++) {
  38487. var modI = i % radialSegments;
  38488. var u = modI / radialSegments * 2 * p * Math.PI;
  38489. var p1 = getPos(u);
  38490. var p2 = getPos(u + 0.01);
  38491. var tang = p2.subtract(p1);
  38492. var n = p2.add(p1);
  38493. var bitan = BABYLON.Vector3.Cross(tang, n);
  38494. n = BABYLON.Vector3.Cross(bitan, tang);
  38495. bitan.normalize();
  38496. n.normalize();
  38497. for (j = 0; j < tubularSegments; j++) {
  38498. var modJ = j % tubularSegments;
  38499. var v = modJ / tubularSegments * 2 * Math.PI;
  38500. var cx = -tube * Math.cos(v);
  38501. var cy = tube * Math.sin(v);
  38502. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38503. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38504. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38505. uvs.push(i / radialSegments);
  38506. uvs.push(j / tubularSegments);
  38507. }
  38508. }
  38509. for (i = 0; i < radialSegments; i++) {
  38510. for (j = 0; j < tubularSegments; j++) {
  38511. var jNext = (j + 1) % tubularSegments;
  38512. var a = i * tubularSegments + j;
  38513. var b = (i + 1) * tubularSegments + j;
  38514. var c = (i + 1) * tubularSegments + jNext;
  38515. var d = i * tubularSegments + jNext;
  38516. indices.push(d);
  38517. indices.push(b);
  38518. indices.push(a);
  38519. indices.push(d);
  38520. indices.push(c);
  38521. indices.push(b);
  38522. }
  38523. }
  38524. // Normals
  38525. VertexData.ComputeNormals(positions, indices, normals);
  38526. // Sides
  38527. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38528. // Result
  38529. var vertexData = new VertexData();
  38530. vertexData.indices = indices;
  38531. vertexData.positions = positions;
  38532. vertexData.normals = normals;
  38533. vertexData.uvs = uvs;
  38534. return vertexData;
  38535. };
  38536. // Tools
  38537. /**
  38538. * Compute normals for given positions and indices
  38539. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38540. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38541. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38542. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38543. * * facetNormals : optional array of facet normals (vector3)
  38544. * * facetPositions : optional array of facet positions (vector3)
  38545. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38546. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38547. * * bInfo : optional bounding info, required for facetPartitioning computation
  38548. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38549. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38550. * * useRightHandedSystem: optional boolean to for right handed system computation
  38551. * * depthSort : optional boolean to enable the facet depth sort computation
  38552. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38553. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38554. */
  38555. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38556. // temporary scalar variables
  38557. var index = 0; // facet index
  38558. var p1p2x = 0.0; // p1p2 vector x coordinate
  38559. var p1p2y = 0.0; // p1p2 vector y coordinate
  38560. var p1p2z = 0.0; // p1p2 vector z coordinate
  38561. var p3p2x = 0.0; // p3p2 vector x coordinate
  38562. var p3p2y = 0.0; // p3p2 vector y coordinate
  38563. var p3p2z = 0.0; // p3p2 vector z coordinate
  38564. var faceNormalx = 0.0; // facet normal x coordinate
  38565. var faceNormaly = 0.0; // facet normal y coordinate
  38566. var faceNormalz = 0.0; // facet normal z coordinate
  38567. var length = 0.0; // facet normal length before normalization
  38568. var v1x = 0; // vector1 x index in the positions array
  38569. var v1y = 0; // vector1 y index in the positions array
  38570. var v1z = 0; // vector1 z index in the positions array
  38571. var v2x = 0; // vector2 x index in the positions array
  38572. var v2y = 0; // vector2 y index in the positions array
  38573. var v2z = 0; // vector2 z index in the positions array
  38574. var v3x = 0; // vector3 x index in the positions array
  38575. var v3y = 0; // vector3 y index in the positions array
  38576. var v3z = 0; // vector3 z index in the positions array
  38577. var computeFacetNormals = false;
  38578. var computeFacetPositions = false;
  38579. var computeFacetPartitioning = false;
  38580. var computeDepthSort = false;
  38581. var faceNormalSign = 1;
  38582. var ratio = 0;
  38583. var distanceTo = null;
  38584. if (options) {
  38585. computeFacetNormals = (options.facetNormals) ? true : false;
  38586. computeFacetPositions = (options.facetPositions) ? true : false;
  38587. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38588. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38589. ratio = options.ratio || 0;
  38590. computeDepthSort = (options.depthSort) ? true : false;
  38591. distanceTo = (options.distanceTo);
  38592. if (computeDepthSort) {
  38593. if (distanceTo === undefined) {
  38594. distanceTo = BABYLON.Vector3.Zero();
  38595. }
  38596. var depthSortedFacets = options.depthSortedFacets;
  38597. }
  38598. }
  38599. // facetPartitioning reinit if needed
  38600. var xSubRatio = 0;
  38601. var ySubRatio = 0;
  38602. var zSubRatio = 0;
  38603. var subSq = 0;
  38604. if (computeFacetPartitioning && options && options.bbSize) {
  38605. var ox = 0; // X partitioning index for facet position
  38606. var oy = 0; // Y partinioning index for facet position
  38607. var oz = 0; // Z partinioning index for facet position
  38608. var b1x = 0; // X partitioning index for facet v1 vertex
  38609. var b1y = 0; // Y partitioning index for facet v1 vertex
  38610. var b1z = 0; // z partitioning index for facet v1 vertex
  38611. var b2x = 0; // X partitioning index for facet v2 vertex
  38612. var b2y = 0; // Y partitioning index for facet v2 vertex
  38613. var b2z = 0; // Z partitioning index for facet v2 vertex
  38614. var b3x = 0; // X partitioning index for facet v3 vertex
  38615. var b3y = 0; // Y partitioning index for facet v3 vertex
  38616. var b3z = 0; // Z partitioning index for facet v3 vertex
  38617. var block_idx_o = 0; // facet barycenter block index
  38618. var block_idx_v1 = 0; // v1 vertex block index
  38619. var block_idx_v2 = 0; // v2 vertex block index
  38620. var block_idx_v3 = 0; // v3 vertex block index
  38621. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38622. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38623. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38624. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38625. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38626. subSq = options.subDiv.max * options.subDiv.max;
  38627. options.facetPartitioning.length = 0;
  38628. }
  38629. // reset the normals
  38630. for (index = 0; index < positions.length; index++) {
  38631. normals[index] = 0.0;
  38632. }
  38633. // Loop : 1 indice triplet = 1 facet
  38634. var nbFaces = (indices.length / 3) | 0;
  38635. for (index = 0; index < nbFaces; index++) {
  38636. // get the indexes of the coordinates of each vertex of the facet
  38637. v1x = indices[index * 3] * 3;
  38638. v1y = v1x + 1;
  38639. v1z = v1x + 2;
  38640. v2x = indices[index * 3 + 1] * 3;
  38641. v2y = v2x + 1;
  38642. v2z = v2x + 2;
  38643. v3x = indices[index * 3 + 2] * 3;
  38644. v3y = v3x + 1;
  38645. v3z = v3x + 2;
  38646. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38647. p1p2y = positions[v1y] - positions[v2y];
  38648. p1p2z = positions[v1z] - positions[v2z];
  38649. p3p2x = positions[v3x] - positions[v2x];
  38650. p3p2y = positions[v3y] - positions[v2y];
  38651. p3p2z = positions[v3z] - positions[v2z];
  38652. // compute the face normal with the cross product
  38653. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38654. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38655. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38656. // normalize this normal and store it in the array facetData
  38657. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38658. length = (length === 0) ? 1.0 : length;
  38659. faceNormalx /= length;
  38660. faceNormaly /= length;
  38661. faceNormalz /= length;
  38662. if (computeFacetNormals && options) {
  38663. options.facetNormals[index].x = faceNormalx;
  38664. options.facetNormals[index].y = faceNormaly;
  38665. options.facetNormals[index].z = faceNormalz;
  38666. }
  38667. if (computeFacetPositions && options) {
  38668. // compute and the facet barycenter coordinates in the array facetPositions
  38669. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38670. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38671. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38672. }
  38673. if (computeFacetPartitioning && options) {
  38674. // store the facet indexes in arrays in the main facetPartitioning array :
  38675. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38676. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38677. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38678. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38679. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38680. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38681. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38682. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38683. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38684. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38685. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38686. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38687. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38688. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38689. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38690. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38691. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38692. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38693. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38694. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38695. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38696. // push each facet index in each block containing the vertex
  38697. options.facetPartitioning[block_idx_v1].push(index);
  38698. if (block_idx_v2 != block_idx_v1) {
  38699. options.facetPartitioning[block_idx_v2].push(index);
  38700. }
  38701. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38702. options.facetPartitioning[block_idx_v3].push(index);
  38703. }
  38704. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38705. options.facetPartitioning[block_idx_o].push(index);
  38706. }
  38707. }
  38708. if (computeDepthSort && options && options.facetPositions) {
  38709. var dsf = depthSortedFacets[index];
  38710. dsf.ind = index * 3;
  38711. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38712. }
  38713. // compute the normals anyway
  38714. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38715. normals[v1y] += faceNormaly;
  38716. normals[v1z] += faceNormalz;
  38717. normals[v2x] += faceNormalx;
  38718. normals[v2y] += faceNormaly;
  38719. normals[v2z] += faceNormalz;
  38720. normals[v3x] += faceNormalx;
  38721. normals[v3y] += faceNormaly;
  38722. normals[v3z] += faceNormalz;
  38723. }
  38724. // last normalization of each normal
  38725. for (index = 0; index < normals.length / 3; index++) {
  38726. faceNormalx = normals[index * 3];
  38727. faceNormaly = normals[index * 3 + 1];
  38728. faceNormalz = normals[index * 3 + 2];
  38729. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38730. length = (length === 0) ? 1.0 : length;
  38731. faceNormalx /= length;
  38732. faceNormaly /= length;
  38733. faceNormalz /= length;
  38734. normals[index * 3] = faceNormalx;
  38735. normals[index * 3 + 1] = faceNormaly;
  38736. normals[index * 3 + 2] = faceNormalz;
  38737. }
  38738. };
  38739. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38740. var li = indices.length;
  38741. var ln = normals.length;
  38742. var i;
  38743. var n;
  38744. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38745. switch (sideOrientation) {
  38746. case BABYLON.Mesh.FRONTSIDE:
  38747. // nothing changed
  38748. break;
  38749. case BABYLON.Mesh.BACKSIDE:
  38750. var tmp;
  38751. // indices
  38752. for (i = 0; i < li; i += 3) {
  38753. tmp = indices[i];
  38754. indices[i] = indices[i + 2];
  38755. indices[i + 2] = tmp;
  38756. }
  38757. // normals
  38758. for (n = 0; n < ln; n++) {
  38759. normals[n] = -normals[n];
  38760. }
  38761. break;
  38762. case BABYLON.Mesh.DOUBLESIDE:
  38763. // positions
  38764. var lp = positions.length;
  38765. var l = lp / 3;
  38766. for (var p = 0; p < lp; p++) {
  38767. positions[lp + p] = positions[p];
  38768. }
  38769. // indices
  38770. for (i = 0; i < li; i += 3) {
  38771. indices[i + li] = indices[i + 2] + l;
  38772. indices[i + 1 + li] = indices[i + 1] + l;
  38773. indices[i + 2 + li] = indices[i] + l;
  38774. }
  38775. // normals
  38776. for (n = 0; n < ln; n++) {
  38777. normals[ln + n] = -normals[n];
  38778. }
  38779. // uvs
  38780. var lu = uvs.length;
  38781. var u = 0;
  38782. for (u = 0; u < lu; u++) {
  38783. uvs[u + lu] = uvs[u];
  38784. }
  38785. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38786. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38787. u = 0;
  38788. for (i = 0; i < lu / 2; i++) {
  38789. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38790. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38791. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38792. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38793. u += 2;
  38794. }
  38795. break;
  38796. }
  38797. };
  38798. /**
  38799. * Applies VertexData created from the imported parameters to the geometry
  38800. * @param parsedVertexData the parsed data from an imported file
  38801. * @param geometry the geometry to apply the VertexData to
  38802. */
  38803. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38804. var vertexData = new VertexData();
  38805. // positions
  38806. var positions = parsedVertexData.positions;
  38807. if (positions) {
  38808. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38809. }
  38810. // normals
  38811. var normals = parsedVertexData.normals;
  38812. if (normals) {
  38813. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38814. }
  38815. // tangents
  38816. var tangents = parsedVertexData.tangents;
  38817. if (tangents) {
  38818. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38819. }
  38820. // uvs
  38821. var uvs = parsedVertexData.uvs;
  38822. if (uvs) {
  38823. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38824. }
  38825. // uv2s
  38826. var uv2s = parsedVertexData.uv2s;
  38827. if (uv2s) {
  38828. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38829. }
  38830. // uv3s
  38831. var uv3s = parsedVertexData.uv3s;
  38832. if (uv3s) {
  38833. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38834. }
  38835. // uv4s
  38836. var uv4s = parsedVertexData.uv4s;
  38837. if (uv4s) {
  38838. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38839. }
  38840. // uv5s
  38841. var uv5s = parsedVertexData.uv5s;
  38842. if (uv5s) {
  38843. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38844. }
  38845. // uv6s
  38846. var uv6s = parsedVertexData.uv6s;
  38847. if (uv6s) {
  38848. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38849. }
  38850. // colors
  38851. var colors = parsedVertexData.colors;
  38852. if (colors) {
  38853. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38854. }
  38855. // matricesIndices
  38856. var matricesIndices = parsedVertexData.matricesIndices;
  38857. if (matricesIndices) {
  38858. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38859. }
  38860. // matricesWeights
  38861. var matricesWeights = parsedVertexData.matricesWeights;
  38862. if (matricesWeights) {
  38863. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38864. }
  38865. // indices
  38866. var indices = parsedVertexData.indices;
  38867. if (indices) {
  38868. vertexData.indices = indices;
  38869. }
  38870. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38871. };
  38872. return VertexData;
  38873. }());
  38874. BABYLON.VertexData = VertexData;
  38875. })(BABYLON || (BABYLON = {}));
  38876. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38877. var BABYLON;
  38878. (function (BABYLON) {
  38879. /**
  38880. * Class used to store geometry data (vertex buffers + index buffer)
  38881. */
  38882. var Geometry = /** @class */ (function () {
  38883. /**
  38884. * Creates a new geometry
  38885. * @param id defines the unique ID
  38886. * @param scene defines the hosting scene
  38887. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38888. * @param updatable defines if geometry must be updatable (false by default)
  38889. * @param mesh defines the mesh that will be associated with the geometry
  38890. */
  38891. function Geometry(id, scene, vertexData, updatable, mesh) {
  38892. if (updatable === void 0) { updatable = false; }
  38893. if (mesh === void 0) { mesh = null; }
  38894. /**
  38895. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38896. */
  38897. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38898. this._totalVertices = 0;
  38899. this._isDisposed = false;
  38900. this._indexBufferIsUpdatable = false;
  38901. this.id = id;
  38902. this._engine = scene.getEngine();
  38903. this._meshes = [];
  38904. this._scene = scene;
  38905. //Init vertex buffer cache
  38906. this._vertexBuffers = {};
  38907. this._indices = [];
  38908. this._updatable = updatable;
  38909. // vertexData
  38910. if (vertexData) {
  38911. this.setAllVerticesData(vertexData, updatable);
  38912. }
  38913. else {
  38914. this._totalVertices = 0;
  38915. this._indices = [];
  38916. }
  38917. if (this._engine.getCaps().vertexArrayObject) {
  38918. this._vertexArrayObjects = {};
  38919. }
  38920. // applyToMesh
  38921. if (mesh) {
  38922. if (mesh.getClassName() === "LinesMesh") {
  38923. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38924. this._updateExtend();
  38925. }
  38926. this.applyToMesh(mesh);
  38927. mesh.computeWorldMatrix(true);
  38928. }
  38929. }
  38930. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38931. /**
  38932. * 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
  38933. */
  38934. get: function () {
  38935. return this._boundingBias;
  38936. },
  38937. /**
  38938. * 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
  38939. */
  38940. set: function (value) {
  38941. if (this._boundingBias && this._boundingBias.equals(value)) {
  38942. return;
  38943. }
  38944. this._boundingBias = value.clone();
  38945. this._updateBoundingInfo(true, null);
  38946. },
  38947. enumerable: true,
  38948. configurable: true
  38949. });
  38950. /**
  38951. * Static function used to attach a new empty geometry to a mesh
  38952. * @param mesh defines the mesh to attach the geometry to
  38953. * @returns the new {BABYLON.Geometry}
  38954. */
  38955. Geometry.CreateGeometryForMesh = function (mesh) {
  38956. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38957. geometry.applyToMesh(mesh);
  38958. return geometry;
  38959. };
  38960. Object.defineProperty(Geometry.prototype, "extend", {
  38961. /**
  38962. * Gets the current extend of the geometry
  38963. */
  38964. get: function () {
  38965. return this._extend;
  38966. },
  38967. enumerable: true,
  38968. configurable: true
  38969. });
  38970. /**
  38971. * Gets the hosting scene
  38972. * @returns the hosting {BABYLON.Scene}
  38973. */
  38974. Geometry.prototype.getScene = function () {
  38975. return this._scene;
  38976. };
  38977. /**
  38978. * Gets the hosting engine
  38979. * @returns the hosting {BABYLON.Engine}
  38980. */
  38981. Geometry.prototype.getEngine = function () {
  38982. return this._engine;
  38983. };
  38984. /**
  38985. * Defines if the geometry is ready to use
  38986. * @returns true if the geometry is ready to be used
  38987. */
  38988. Geometry.prototype.isReady = function () {
  38989. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38990. };
  38991. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38992. /**
  38993. * Gets a value indicating that the geometry should not be serialized
  38994. */
  38995. get: function () {
  38996. for (var index = 0; index < this._meshes.length; index++) {
  38997. if (!this._meshes[index].doNotSerialize) {
  38998. return false;
  38999. }
  39000. }
  39001. return true;
  39002. },
  39003. enumerable: true,
  39004. configurable: true
  39005. });
  39006. /** @hidden */
  39007. Geometry.prototype._rebuild = function () {
  39008. if (this._vertexArrayObjects) {
  39009. this._vertexArrayObjects = {};
  39010. }
  39011. // Index buffer
  39012. if (this._meshes.length !== 0 && this._indices) {
  39013. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39014. }
  39015. // Vertex buffers
  39016. for (var key in this._vertexBuffers) {
  39017. var vertexBuffer = this._vertexBuffers[key];
  39018. vertexBuffer._rebuild();
  39019. }
  39020. };
  39021. /**
  39022. * Affects all geometry data in one call
  39023. * @param vertexData defines the geometry data
  39024. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39025. */
  39026. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39027. vertexData.applyToGeometry(this, updatable);
  39028. this.notifyUpdate();
  39029. };
  39030. /**
  39031. * Set specific vertex data
  39032. * @param kind defines the data kind (Position, normal, etc...)
  39033. * @param data defines the vertex data to use
  39034. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39035. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39036. */
  39037. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39038. if (updatable === void 0) { updatable = false; }
  39039. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39040. this.setVerticesBuffer(buffer);
  39041. };
  39042. /**
  39043. * Removes a specific vertex data
  39044. * @param kind defines the data kind (Position, normal, etc...)
  39045. */
  39046. Geometry.prototype.removeVerticesData = function (kind) {
  39047. if (this._vertexBuffers[kind]) {
  39048. this._vertexBuffers[kind].dispose();
  39049. delete this._vertexBuffers[kind];
  39050. }
  39051. };
  39052. /**
  39053. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39054. * @param buffer defines the vertex buffer to use
  39055. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39056. */
  39057. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39058. if (totalVertices === void 0) { totalVertices = null; }
  39059. var kind = buffer.getKind();
  39060. if (this._vertexBuffers[kind]) {
  39061. this._vertexBuffers[kind].dispose();
  39062. }
  39063. this._vertexBuffers[kind] = buffer;
  39064. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39065. var data = buffer.getData();
  39066. if (totalVertices != null) {
  39067. this._totalVertices = totalVertices;
  39068. }
  39069. else {
  39070. if (data != null) {
  39071. this._totalVertices = data.length / (buffer.byteStride / 4);
  39072. }
  39073. }
  39074. this._updateExtend(data);
  39075. this._resetPointsArrayCache();
  39076. var meshes = this._meshes;
  39077. var numOfMeshes = meshes.length;
  39078. for (var index = 0; index < numOfMeshes; index++) {
  39079. var mesh = meshes[index];
  39080. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39081. mesh._createGlobalSubMesh(false);
  39082. mesh.computeWorldMatrix(true);
  39083. }
  39084. }
  39085. this.notifyUpdate(kind);
  39086. if (this._vertexArrayObjects) {
  39087. this._disposeVertexArrayObjects();
  39088. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39089. }
  39090. };
  39091. /**
  39092. * Update a specific vertex buffer
  39093. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39094. * It will do nothing if the buffer is not updatable
  39095. * @param kind defines the data kind (Position, normal, etc...)
  39096. * @param data defines the data to use
  39097. * @param offset defines the offset in the target buffer where to store the data
  39098. * @param useBytes set to true if the offset is in bytes
  39099. */
  39100. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39101. if (useBytes === void 0) { useBytes = false; }
  39102. var vertexBuffer = this.getVertexBuffer(kind);
  39103. if (!vertexBuffer) {
  39104. return;
  39105. }
  39106. vertexBuffer.updateDirectly(data, offset, useBytes);
  39107. this.notifyUpdate(kind);
  39108. };
  39109. /**
  39110. * Update a specific vertex buffer
  39111. * This function will create a new buffer if the current one is not updatable
  39112. * @param kind defines the data kind (Position, normal, etc...)
  39113. * @param data defines the data to use
  39114. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39115. */
  39116. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39117. if (updateExtends === void 0) { updateExtends = false; }
  39118. var vertexBuffer = this.getVertexBuffer(kind);
  39119. if (!vertexBuffer) {
  39120. return;
  39121. }
  39122. vertexBuffer.update(data);
  39123. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39124. this._updateBoundingInfo(updateExtends, data);
  39125. }
  39126. this.notifyUpdate(kind);
  39127. };
  39128. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39129. if (updateExtends) {
  39130. this._updateExtend(data);
  39131. }
  39132. var meshes = this._meshes;
  39133. var numOfMeshes = meshes.length;
  39134. this._resetPointsArrayCache();
  39135. for (var index = 0; index < numOfMeshes; index++) {
  39136. var mesh = meshes[index];
  39137. if (updateExtends) {
  39138. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39139. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39140. var subMesh = mesh.subMeshes[subIndex];
  39141. subMesh.refreshBoundingInfo();
  39142. }
  39143. }
  39144. }
  39145. };
  39146. /** @hidden */
  39147. Geometry.prototype._bind = function (effect, indexToBind) {
  39148. if (!effect) {
  39149. return;
  39150. }
  39151. if (indexToBind === undefined) {
  39152. indexToBind = this._indexBuffer;
  39153. }
  39154. var vbs = this.getVertexBuffers();
  39155. if (!vbs) {
  39156. return;
  39157. }
  39158. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39159. this._engine.bindBuffers(vbs, indexToBind, effect);
  39160. return;
  39161. }
  39162. // Using VAO
  39163. if (!this._vertexArrayObjects[effect.key]) {
  39164. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39165. }
  39166. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39167. };
  39168. /**
  39169. * Gets total number of vertices
  39170. * @returns the total number of vertices
  39171. */
  39172. Geometry.prototype.getTotalVertices = function () {
  39173. if (!this.isReady()) {
  39174. return 0;
  39175. }
  39176. return this._totalVertices;
  39177. };
  39178. /**
  39179. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39180. * @param kind defines the data kind (Position, normal, etc...)
  39181. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39182. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39183. * @returns a float array containing vertex data
  39184. */
  39185. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39186. var vertexBuffer = this.getVertexBuffer(kind);
  39187. if (!vertexBuffer) {
  39188. return null;
  39189. }
  39190. var data = vertexBuffer.getData();
  39191. if (!data) {
  39192. return null;
  39193. }
  39194. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39195. var count = this._totalVertices * vertexBuffer.getSize();
  39196. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39197. var copy_1 = new Array(count);
  39198. vertexBuffer.forEach(count, function (value, index) {
  39199. copy_1[index] = value;
  39200. });
  39201. return copy_1;
  39202. }
  39203. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39204. if (data instanceof Array) {
  39205. var offset = vertexBuffer.byteOffset / 4;
  39206. return BABYLON.Tools.Slice(data, offset, offset + count);
  39207. }
  39208. else if (data instanceof ArrayBuffer) {
  39209. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39210. }
  39211. else {
  39212. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39213. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39214. var result = new Float32Array(count);
  39215. var source = new Float32Array(data.buffer, offset, count);
  39216. result.set(source);
  39217. return result;
  39218. }
  39219. return new Float32Array(data.buffer, offset, count);
  39220. }
  39221. }
  39222. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39223. return BABYLON.Tools.Slice(data);
  39224. }
  39225. return data;
  39226. };
  39227. /**
  39228. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39229. * @param kind defines the data kind (Position, normal, etc...)
  39230. * @returns true if the vertex buffer with the specified kind is updatable
  39231. */
  39232. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39233. var vb = this._vertexBuffers[kind];
  39234. if (!vb) {
  39235. return false;
  39236. }
  39237. return vb.isUpdatable();
  39238. };
  39239. /**
  39240. * Gets a specific vertex buffer
  39241. * @param kind defines the data kind (Position, normal, etc...)
  39242. * @returns a {BABYLON.VertexBuffer}
  39243. */
  39244. Geometry.prototype.getVertexBuffer = function (kind) {
  39245. if (!this.isReady()) {
  39246. return null;
  39247. }
  39248. return this._vertexBuffers[kind];
  39249. };
  39250. /**
  39251. * Returns all vertex buffers
  39252. * @return an object holding all vertex buffers indexed by kind
  39253. */
  39254. Geometry.prototype.getVertexBuffers = function () {
  39255. if (!this.isReady()) {
  39256. return null;
  39257. }
  39258. return this._vertexBuffers;
  39259. };
  39260. /**
  39261. * Gets a boolean indicating if specific vertex buffer is present
  39262. * @param kind defines the data kind (Position, normal, etc...)
  39263. * @returns true if data is present
  39264. */
  39265. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39266. if (!this._vertexBuffers) {
  39267. if (this._delayInfo) {
  39268. return this._delayInfo.indexOf(kind) !== -1;
  39269. }
  39270. return false;
  39271. }
  39272. return this._vertexBuffers[kind] !== undefined;
  39273. };
  39274. /**
  39275. * Gets a list of all attached data kinds (Position, normal, etc...)
  39276. * @returns a list of string containing all kinds
  39277. */
  39278. Geometry.prototype.getVerticesDataKinds = function () {
  39279. var result = [];
  39280. var kind;
  39281. if (!this._vertexBuffers && this._delayInfo) {
  39282. for (kind in this._delayInfo) {
  39283. result.push(kind);
  39284. }
  39285. }
  39286. else {
  39287. for (kind in this._vertexBuffers) {
  39288. result.push(kind);
  39289. }
  39290. }
  39291. return result;
  39292. };
  39293. /**
  39294. * Update index buffer
  39295. * @param indices defines the indices to store in the index buffer
  39296. * @param offset defines the offset in the target buffer where to store the data
  39297. */
  39298. Geometry.prototype.updateIndices = function (indices, offset) {
  39299. if (!this._indexBuffer) {
  39300. return;
  39301. }
  39302. if (!this._indexBufferIsUpdatable) {
  39303. this.setIndices(indices, null, true);
  39304. }
  39305. else {
  39306. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39307. }
  39308. };
  39309. /**
  39310. * Creates a new index buffer
  39311. * @param indices defines the indices to store in the index buffer
  39312. * @param totalVertices defines the total number of vertices (could be null)
  39313. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39314. */
  39315. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39316. if (totalVertices === void 0) { totalVertices = null; }
  39317. if (updatable === void 0) { updatable = false; }
  39318. if (this._indexBuffer) {
  39319. this._engine._releaseBuffer(this._indexBuffer);
  39320. }
  39321. this._disposeVertexArrayObjects();
  39322. this._indices = indices;
  39323. this._indexBufferIsUpdatable = updatable;
  39324. if (this._meshes.length !== 0 && this._indices) {
  39325. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39326. }
  39327. if (totalVertices != undefined) { // including null and undefined
  39328. this._totalVertices = totalVertices;
  39329. }
  39330. var meshes = this._meshes;
  39331. var numOfMeshes = meshes.length;
  39332. for (var index = 0; index < numOfMeshes; index++) {
  39333. meshes[index]._createGlobalSubMesh(true);
  39334. }
  39335. this.notifyUpdate();
  39336. };
  39337. /**
  39338. * Return the total number of indices
  39339. * @returns the total number of indices
  39340. */
  39341. Geometry.prototype.getTotalIndices = function () {
  39342. if (!this.isReady()) {
  39343. return 0;
  39344. }
  39345. return this._indices.length;
  39346. };
  39347. /**
  39348. * Gets the index buffer array
  39349. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39350. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39351. * @returns the index buffer array
  39352. */
  39353. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39354. if (!this.isReady()) {
  39355. return null;
  39356. }
  39357. var orig = this._indices;
  39358. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39359. return orig;
  39360. }
  39361. else {
  39362. var len = orig.length;
  39363. var copy = [];
  39364. for (var i = 0; i < len; i++) {
  39365. copy.push(orig[i]);
  39366. }
  39367. return copy;
  39368. }
  39369. };
  39370. /**
  39371. * Gets the index buffer
  39372. * @return the index buffer
  39373. */
  39374. Geometry.prototype.getIndexBuffer = function () {
  39375. if (!this.isReady()) {
  39376. return null;
  39377. }
  39378. return this._indexBuffer;
  39379. };
  39380. /** @hidden */
  39381. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39382. if (effect === void 0) { effect = null; }
  39383. if (!effect || !this._vertexArrayObjects) {
  39384. return;
  39385. }
  39386. if (this._vertexArrayObjects[effect.key]) {
  39387. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39388. delete this._vertexArrayObjects[effect.key];
  39389. }
  39390. };
  39391. /**
  39392. * Release the associated resources for a specific mesh
  39393. * @param mesh defines the source mesh
  39394. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39395. */
  39396. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39397. var meshes = this._meshes;
  39398. var index = meshes.indexOf(mesh);
  39399. if (index === -1) {
  39400. return;
  39401. }
  39402. meshes.splice(index, 1);
  39403. mesh._geometry = null;
  39404. if (meshes.length === 0 && shouldDispose) {
  39405. this.dispose();
  39406. }
  39407. };
  39408. /**
  39409. * Apply current geometry to a given mesh
  39410. * @param mesh defines the mesh to apply geometry to
  39411. */
  39412. Geometry.prototype.applyToMesh = function (mesh) {
  39413. if (mesh._geometry === this) {
  39414. return;
  39415. }
  39416. var previousGeometry = mesh._geometry;
  39417. if (previousGeometry) {
  39418. previousGeometry.releaseForMesh(mesh);
  39419. }
  39420. var meshes = this._meshes;
  39421. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39422. mesh._geometry = this;
  39423. this._scene.pushGeometry(this);
  39424. meshes.push(mesh);
  39425. if (this.isReady()) {
  39426. this._applyToMesh(mesh);
  39427. }
  39428. else {
  39429. mesh._boundingInfo = this._boundingInfo;
  39430. }
  39431. };
  39432. Geometry.prototype._updateExtend = function (data) {
  39433. if (data === void 0) { data = null; }
  39434. if (!data) {
  39435. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39436. }
  39437. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39438. };
  39439. Geometry.prototype._applyToMesh = function (mesh) {
  39440. var numOfMeshes = this._meshes.length;
  39441. // vertexBuffers
  39442. for (var kind in this._vertexBuffers) {
  39443. if (numOfMeshes === 1) {
  39444. this._vertexBuffers[kind].create();
  39445. }
  39446. var buffer = this._vertexBuffers[kind].getBuffer();
  39447. if (buffer)
  39448. buffer.references = numOfMeshes;
  39449. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39450. if (!this._extend) {
  39451. this._updateExtend();
  39452. }
  39453. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39454. mesh._createGlobalSubMesh(false);
  39455. //bounding info was just created again, world matrix should be applied again.
  39456. mesh._updateBoundingInfo();
  39457. }
  39458. }
  39459. // indexBuffer
  39460. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39461. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39462. }
  39463. if (this._indexBuffer) {
  39464. this._indexBuffer.references = numOfMeshes;
  39465. }
  39466. };
  39467. Geometry.prototype.notifyUpdate = function (kind) {
  39468. if (this.onGeometryUpdated) {
  39469. this.onGeometryUpdated(this, kind);
  39470. }
  39471. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39472. var mesh = _a[_i];
  39473. mesh._markSubMeshesAsAttributesDirty();
  39474. }
  39475. };
  39476. /**
  39477. * Load the geometry if it was flagged as delay loaded
  39478. * @param scene defines the hosting scene
  39479. * @param onLoaded defines a callback called when the geometry is loaded
  39480. */
  39481. Geometry.prototype.load = function (scene, onLoaded) {
  39482. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39483. return;
  39484. }
  39485. if (this.isReady()) {
  39486. if (onLoaded) {
  39487. onLoaded();
  39488. }
  39489. return;
  39490. }
  39491. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39492. this._queueLoad(scene, onLoaded);
  39493. };
  39494. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39495. var _this = this;
  39496. if (!this.delayLoadingFile) {
  39497. return;
  39498. }
  39499. scene._addPendingData(this);
  39500. scene._loadFile(this.delayLoadingFile, function (data) {
  39501. if (!_this._delayLoadingFunction) {
  39502. return;
  39503. }
  39504. _this._delayLoadingFunction(JSON.parse(data), _this);
  39505. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39506. _this._delayInfo = [];
  39507. scene._removePendingData(_this);
  39508. var meshes = _this._meshes;
  39509. var numOfMeshes = meshes.length;
  39510. for (var index = 0; index < numOfMeshes; index++) {
  39511. _this._applyToMesh(meshes[index]);
  39512. }
  39513. if (onLoaded) {
  39514. onLoaded();
  39515. }
  39516. }, undefined, true);
  39517. };
  39518. /**
  39519. * Invert the geometry to move from a right handed system to a left handed one.
  39520. */
  39521. Geometry.prototype.toLeftHanded = function () {
  39522. // Flip faces
  39523. var tIndices = this.getIndices(false);
  39524. if (tIndices != null && tIndices.length > 0) {
  39525. for (var i = 0; i < tIndices.length; i += 3) {
  39526. var tTemp = tIndices[i + 0];
  39527. tIndices[i + 0] = tIndices[i + 2];
  39528. tIndices[i + 2] = tTemp;
  39529. }
  39530. this.setIndices(tIndices);
  39531. }
  39532. // Negate position.z
  39533. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39534. if (tPositions != null && tPositions.length > 0) {
  39535. for (var i = 0; i < tPositions.length; i += 3) {
  39536. tPositions[i + 2] = -tPositions[i + 2];
  39537. }
  39538. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39539. }
  39540. // Negate normal.z
  39541. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39542. if (tNormals != null && tNormals.length > 0) {
  39543. for (var i = 0; i < tNormals.length; i += 3) {
  39544. tNormals[i + 2] = -tNormals[i + 2];
  39545. }
  39546. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39547. }
  39548. };
  39549. // Cache
  39550. /** @hidden */
  39551. Geometry.prototype._resetPointsArrayCache = function () {
  39552. this._positions = null;
  39553. };
  39554. /** @hidden */
  39555. Geometry.prototype._generatePointsArray = function () {
  39556. if (this._positions)
  39557. return true;
  39558. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39559. if (!data || data.length === 0) {
  39560. return false;
  39561. }
  39562. this._positions = [];
  39563. for (var index = 0; index < data.length; index += 3) {
  39564. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39565. }
  39566. return true;
  39567. };
  39568. /**
  39569. * Gets a value indicating if the geometry is disposed
  39570. * @returns true if the geometry was disposed
  39571. */
  39572. Geometry.prototype.isDisposed = function () {
  39573. return this._isDisposed;
  39574. };
  39575. Geometry.prototype._disposeVertexArrayObjects = function () {
  39576. if (this._vertexArrayObjects) {
  39577. for (var kind in this._vertexArrayObjects) {
  39578. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39579. }
  39580. this._vertexArrayObjects = {};
  39581. }
  39582. };
  39583. /**
  39584. * Free all associated resources
  39585. */
  39586. Geometry.prototype.dispose = function () {
  39587. var meshes = this._meshes;
  39588. var numOfMeshes = meshes.length;
  39589. var index;
  39590. for (index = 0; index < numOfMeshes; index++) {
  39591. this.releaseForMesh(meshes[index]);
  39592. }
  39593. this._meshes = [];
  39594. this._disposeVertexArrayObjects();
  39595. for (var kind in this._vertexBuffers) {
  39596. this._vertexBuffers[kind].dispose();
  39597. }
  39598. this._vertexBuffers = {};
  39599. this._totalVertices = 0;
  39600. if (this._indexBuffer) {
  39601. this._engine._releaseBuffer(this._indexBuffer);
  39602. }
  39603. this._indexBuffer = null;
  39604. this._indices = [];
  39605. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39606. this.delayLoadingFile = null;
  39607. this._delayLoadingFunction = null;
  39608. this._delayInfo = [];
  39609. this._boundingInfo = null;
  39610. this._scene.removeGeometry(this);
  39611. this._isDisposed = true;
  39612. };
  39613. /**
  39614. * Clone the current geometry into a new geometry
  39615. * @param id defines the unique ID of the new geometry
  39616. * @returns a new geometry object
  39617. */
  39618. Geometry.prototype.copy = function (id) {
  39619. var vertexData = new BABYLON.VertexData();
  39620. vertexData.indices = [];
  39621. var indices = this.getIndices();
  39622. if (indices) {
  39623. for (var index = 0; index < indices.length; index++) {
  39624. vertexData.indices.push(indices[index]);
  39625. }
  39626. }
  39627. var updatable = false;
  39628. var stopChecking = false;
  39629. var kind;
  39630. for (kind in this._vertexBuffers) {
  39631. // using slice() to make a copy of the array and not just reference it
  39632. var data = this.getVerticesData(kind);
  39633. if (data instanceof Float32Array) {
  39634. vertexData.set(new Float32Array(data), kind);
  39635. }
  39636. else {
  39637. vertexData.set(data.slice(0), kind);
  39638. }
  39639. if (!stopChecking) {
  39640. var vb = this.getVertexBuffer(kind);
  39641. if (vb) {
  39642. updatable = vb.isUpdatable();
  39643. stopChecking = !updatable;
  39644. }
  39645. }
  39646. }
  39647. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39648. geometry.delayLoadState = this.delayLoadState;
  39649. geometry.delayLoadingFile = this.delayLoadingFile;
  39650. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39651. for (kind in this._delayInfo) {
  39652. geometry._delayInfo = geometry._delayInfo || [];
  39653. geometry._delayInfo.push(kind);
  39654. }
  39655. // Bounding info
  39656. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39657. return geometry;
  39658. };
  39659. /**
  39660. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39661. * @return a JSON representation of the current geometry data (without the vertices data)
  39662. */
  39663. Geometry.prototype.serialize = function () {
  39664. var serializationObject = {};
  39665. serializationObject.id = this.id;
  39666. serializationObject.updatable = this._updatable;
  39667. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39668. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39669. }
  39670. return serializationObject;
  39671. };
  39672. Geometry.prototype.toNumberArray = function (origin) {
  39673. if (Array.isArray(origin)) {
  39674. return origin;
  39675. }
  39676. else {
  39677. return Array.prototype.slice.call(origin);
  39678. }
  39679. };
  39680. /**
  39681. * Serialize all vertices data into a JSON oject
  39682. * @returns a JSON representation of the current geometry data
  39683. */
  39684. Geometry.prototype.serializeVerticeData = function () {
  39685. var serializationObject = this.serialize();
  39686. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39687. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39688. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39689. serializationObject.positions._updatable = true;
  39690. }
  39691. }
  39692. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39693. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39694. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39695. serializationObject.normals._updatable = true;
  39696. }
  39697. }
  39698. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39699. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39700. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39701. serializationObject.tangets._updatable = true;
  39702. }
  39703. }
  39704. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39705. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39706. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39707. serializationObject.uvs._updatable = true;
  39708. }
  39709. }
  39710. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39711. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39712. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39713. serializationObject.uv2s._updatable = true;
  39714. }
  39715. }
  39716. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39717. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39718. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39719. serializationObject.uv3s._updatable = true;
  39720. }
  39721. }
  39722. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39723. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39724. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39725. serializationObject.uv4s._updatable = true;
  39726. }
  39727. }
  39728. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39729. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39730. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39731. serializationObject.uv5s._updatable = true;
  39732. }
  39733. }
  39734. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39735. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39736. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39737. serializationObject.uv6s._updatable = true;
  39738. }
  39739. }
  39740. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39741. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39742. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39743. serializationObject.colors._updatable = true;
  39744. }
  39745. }
  39746. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39747. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39748. serializationObject.matricesIndices._isExpanded = true;
  39749. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39750. serializationObject.matricesIndices._updatable = true;
  39751. }
  39752. }
  39753. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39754. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39755. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39756. serializationObject.matricesWeights._updatable = true;
  39757. }
  39758. }
  39759. serializationObject.indices = this.toNumberArray(this.getIndices());
  39760. return serializationObject;
  39761. };
  39762. // Statics
  39763. /**
  39764. * Extracts a clone of a mesh geometry
  39765. * @param mesh defines the source mesh
  39766. * @param id defines the unique ID of the new geometry object
  39767. * @returns the new geometry object
  39768. */
  39769. Geometry.ExtractFromMesh = function (mesh, id) {
  39770. var geometry = mesh._geometry;
  39771. if (!geometry) {
  39772. return null;
  39773. }
  39774. return geometry.copy(id);
  39775. };
  39776. /**
  39777. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39778. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39779. * Be aware Math.random() could cause collisions, but:
  39780. * "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"
  39781. * @returns a string containing a new GUID
  39782. */
  39783. Geometry.RandomId = function () {
  39784. return BABYLON.Tools.RandomId();
  39785. };
  39786. /** @hidden */
  39787. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39788. var scene = mesh.getScene();
  39789. // Geometry
  39790. var geometryId = parsedGeometry.geometryId;
  39791. if (geometryId) {
  39792. var geometry = scene.getGeometryByID(geometryId);
  39793. if (geometry) {
  39794. geometry.applyToMesh(mesh);
  39795. }
  39796. }
  39797. else if (parsedGeometry instanceof ArrayBuffer) {
  39798. var binaryInfo = mesh._binaryInfo;
  39799. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39800. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39801. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39802. }
  39803. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39804. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39805. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39806. }
  39807. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39808. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39809. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39810. }
  39811. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39812. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39813. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39814. }
  39815. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39816. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39817. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39818. }
  39819. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39820. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39821. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39822. }
  39823. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39824. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39825. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39826. }
  39827. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39828. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39829. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39830. }
  39831. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39832. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39833. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39834. }
  39835. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39836. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39837. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39838. }
  39839. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39840. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39841. var floatIndices = [];
  39842. for (var i = 0; i < matricesIndicesData.length; i++) {
  39843. var index = matricesIndicesData[i];
  39844. floatIndices.push(index & 0x000000FF);
  39845. floatIndices.push((index & 0x0000FF00) >> 8);
  39846. floatIndices.push((index & 0x00FF0000) >> 16);
  39847. floatIndices.push(index >> 24);
  39848. }
  39849. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39850. }
  39851. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39852. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39853. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39854. }
  39855. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39856. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39857. mesh.setIndices(indicesData, null);
  39858. }
  39859. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39860. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39861. mesh.subMeshes = [];
  39862. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39863. var materialIndex = subMeshesData[(i * 5) + 0];
  39864. var verticesStart = subMeshesData[(i * 5) + 1];
  39865. var verticesCount = subMeshesData[(i * 5) + 2];
  39866. var indexStart = subMeshesData[(i * 5) + 3];
  39867. var indexCount = subMeshesData[(i * 5) + 4];
  39868. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39869. }
  39870. }
  39871. }
  39872. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39873. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39874. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39875. if (parsedGeometry.tangents) {
  39876. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39877. }
  39878. if (parsedGeometry.uvs) {
  39879. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39880. }
  39881. if (parsedGeometry.uvs2) {
  39882. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39883. }
  39884. if (parsedGeometry.uvs3) {
  39885. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39886. }
  39887. if (parsedGeometry.uvs4) {
  39888. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39889. }
  39890. if (parsedGeometry.uvs5) {
  39891. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39892. }
  39893. if (parsedGeometry.uvs6) {
  39894. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39895. }
  39896. if (parsedGeometry.colors) {
  39897. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39898. }
  39899. if (parsedGeometry.matricesIndices) {
  39900. if (!parsedGeometry.matricesIndices._isExpanded) {
  39901. var floatIndices = [];
  39902. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39903. var matricesIndex = parsedGeometry.matricesIndices[i];
  39904. floatIndices.push(matricesIndex & 0x000000FF);
  39905. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39906. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39907. floatIndices.push(matricesIndex >> 24);
  39908. }
  39909. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39910. }
  39911. else {
  39912. delete parsedGeometry.matricesIndices._isExpanded;
  39913. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39914. }
  39915. }
  39916. if (parsedGeometry.matricesIndicesExtra) {
  39917. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39918. var floatIndices = [];
  39919. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39920. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39921. floatIndices.push(matricesIndex & 0x000000FF);
  39922. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39923. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39924. floatIndices.push(matricesIndex >> 24);
  39925. }
  39926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39927. }
  39928. else {
  39929. delete parsedGeometry.matricesIndices._isExpanded;
  39930. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39931. }
  39932. }
  39933. if (parsedGeometry.matricesWeights) {
  39934. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39935. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39936. }
  39937. if (parsedGeometry.matricesWeightsExtra) {
  39938. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39939. }
  39940. mesh.setIndices(parsedGeometry.indices, null);
  39941. }
  39942. // SubMeshes
  39943. if (parsedGeometry.subMeshes) {
  39944. mesh.subMeshes = [];
  39945. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39946. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39947. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39948. }
  39949. }
  39950. // Flat shading
  39951. if (mesh._shouldGenerateFlatShading) {
  39952. mesh.convertToFlatShadedMesh();
  39953. delete mesh._shouldGenerateFlatShading;
  39954. }
  39955. // Update
  39956. mesh.computeWorldMatrix(true);
  39957. // Octree
  39958. var sceneOctree = scene.selectionOctree;
  39959. if (sceneOctree !== undefined && sceneOctree !== null) {
  39960. sceneOctree.addMesh(mesh);
  39961. }
  39962. };
  39963. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39964. var epsilon = 1e-3;
  39965. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39966. return;
  39967. }
  39968. var noInfluenceBoneIndex = 0.0;
  39969. if (parsedGeometry.skeletonId > -1) {
  39970. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39971. if (!skeleton) {
  39972. return;
  39973. }
  39974. noInfluenceBoneIndex = skeleton.bones.length;
  39975. }
  39976. else {
  39977. return;
  39978. }
  39979. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39980. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39981. var matricesWeights = parsedGeometry.matricesWeights;
  39982. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39983. var influencers = parsedGeometry.numBoneInfluencer;
  39984. var size = matricesWeights.length;
  39985. for (var i = 0; i < size; i += 4) {
  39986. var weight = 0.0;
  39987. var firstZeroWeight = -1;
  39988. for (var j = 0; j < 4; j++) {
  39989. var w = matricesWeights[i + j];
  39990. weight += w;
  39991. if (w < epsilon && firstZeroWeight < 0) {
  39992. firstZeroWeight = j;
  39993. }
  39994. }
  39995. if (matricesWeightsExtra) {
  39996. for (var j = 0; j < 4; j++) {
  39997. var w = matricesWeightsExtra[i + j];
  39998. weight += w;
  39999. if (w < epsilon && firstZeroWeight < 0) {
  40000. firstZeroWeight = j + 4;
  40001. }
  40002. }
  40003. }
  40004. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40005. firstZeroWeight = influencers - 1;
  40006. }
  40007. if (weight > epsilon) {
  40008. var mweight = 1.0 / weight;
  40009. for (var j = 0; j < 4; j++) {
  40010. matricesWeights[i + j] *= mweight;
  40011. }
  40012. if (matricesWeightsExtra) {
  40013. for (var j = 0; j < 4; j++) {
  40014. matricesWeightsExtra[i + j] *= mweight;
  40015. }
  40016. }
  40017. }
  40018. else {
  40019. if (firstZeroWeight >= 4) {
  40020. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40021. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40022. }
  40023. else {
  40024. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40025. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40026. }
  40027. }
  40028. }
  40029. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40030. if (parsedGeometry.matricesWeightsExtra) {
  40031. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40032. }
  40033. };
  40034. /**
  40035. * Create a new geometry from persisted data (Using .babylon file format)
  40036. * @param parsedVertexData defines the persisted data
  40037. * @param scene defines the hosting scene
  40038. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40039. * @returns the new geometry object
  40040. */
  40041. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40042. if (scene.getGeometryByID(parsedVertexData.id)) {
  40043. return null; // null since geometry could be something else than a box...
  40044. }
  40045. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40046. if (BABYLON.Tags) {
  40047. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40048. }
  40049. if (parsedVertexData.delayLoadingFile) {
  40050. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40051. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40052. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40053. geometry._delayInfo = [];
  40054. if (parsedVertexData.hasUVs) {
  40055. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40056. }
  40057. if (parsedVertexData.hasUVs2) {
  40058. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40059. }
  40060. if (parsedVertexData.hasUVs3) {
  40061. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40062. }
  40063. if (parsedVertexData.hasUVs4) {
  40064. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40065. }
  40066. if (parsedVertexData.hasUVs5) {
  40067. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40068. }
  40069. if (parsedVertexData.hasUVs6) {
  40070. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40071. }
  40072. if (parsedVertexData.hasColors) {
  40073. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40074. }
  40075. if (parsedVertexData.hasMatricesIndices) {
  40076. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40077. }
  40078. if (parsedVertexData.hasMatricesWeights) {
  40079. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40080. }
  40081. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40082. }
  40083. else {
  40084. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40085. }
  40086. scene.pushGeometry(geometry, true);
  40087. return geometry;
  40088. };
  40089. return Geometry;
  40090. }());
  40091. BABYLON.Geometry = Geometry;
  40092. // Primitives
  40093. /// Abstract class
  40094. /**
  40095. * Abstract class used to provide common services for all typed geometries
  40096. * @hidden
  40097. */
  40098. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40099. __extends(_PrimitiveGeometry, _super);
  40100. /**
  40101. * Creates a new typed geometry
  40102. * @param id defines the unique ID of the geometry
  40103. * @param scene defines the hosting scene
  40104. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40105. * @param mesh defines the hosting mesh (can be null)
  40106. */
  40107. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40108. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40109. if (mesh === void 0) { mesh = null; }
  40110. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40111. _this._canBeRegenerated = _canBeRegenerated;
  40112. _this._beingRegenerated = true;
  40113. _this.regenerate();
  40114. _this._beingRegenerated = false;
  40115. return _this;
  40116. }
  40117. /**
  40118. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40119. * @returns true if the geometry can be regenerated
  40120. */
  40121. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40122. return this._canBeRegenerated;
  40123. };
  40124. /**
  40125. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40126. */
  40127. _PrimitiveGeometry.prototype.regenerate = function () {
  40128. if (!this._canBeRegenerated) {
  40129. return;
  40130. }
  40131. this._beingRegenerated = true;
  40132. this.setAllVerticesData(this._regenerateVertexData(), false);
  40133. this._beingRegenerated = false;
  40134. };
  40135. /**
  40136. * Clone the geometry
  40137. * @param id defines the unique ID of the new geometry
  40138. * @returns the new geometry
  40139. */
  40140. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40141. return _super.prototype.copy.call(this, id);
  40142. };
  40143. // overrides
  40144. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40145. if (!this._beingRegenerated) {
  40146. return;
  40147. }
  40148. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40149. };
  40150. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40151. if (!this._beingRegenerated) {
  40152. return;
  40153. }
  40154. _super.prototype.setVerticesData.call(this, kind, data, false);
  40155. };
  40156. // to override
  40157. /** @hidden */
  40158. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40159. throw new Error("Abstract method");
  40160. };
  40161. _PrimitiveGeometry.prototype.copy = function (id) {
  40162. throw new Error("Must be overriden in sub-classes.");
  40163. };
  40164. _PrimitiveGeometry.prototype.serialize = function () {
  40165. var serializationObject = _super.prototype.serialize.call(this);
  40166. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40167. return serializationObject;
  40168. };
  40169. return _PrimitiveGeometry;
  40170. }(Geometry));
  40171. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40172. /**
  40173. * Creates a ribbon geometry
  40174. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40175. */
  40176. var RibbonGeometry = /** @class */ (function (_super) {
  40177. __extends(RibbonGeometry, _super);
  40178. /**
  40179. * Creates a ribbon geometry
  40180. * @param id defines the unique ID of the geometry
  40181. * @param scene defines the hosting scene
  40182. * @param pathArray defines the array of paths to use
  40183. * @param closeArray defines if the last path and the first path must be joined
  40184. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40185. * @param offset defines the offset between points
  40186. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40187. * @param mesh defines the hosting mesh (can be null)
  40188. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40189. */
  40190. function RibbonGeometry(id, scene,
  40191. /**
  40192. * Defines the array of paths to use
  40193. */
  40194. pathArray,
  40195. /**
  40196. * Defines if the last and first points of each path in your pathArray must be joined
  40197. */
  40198. closeArray,
  40199. /**
  40200. * Defines if the last and first points of each path in your pathArray must be joined
  40201. */
  40202. closePath,
  40203. /**
  40204. * Defines the offset between points
  40205. */
  40206. offset, canBeRegenerated, mesh,
  40207. /**
  40208. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40209. */
  40210. side) {
  40211. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40212. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40213. _this.pathArray = pathArray;
  40214. _this.closeArray = closeArray;
  40215. _this.closePath = closePath;
  40216. _this.offset = offset;
  40217. _this.side = side;
  40218. return _this;
  40219. }
  40220. /** @hidden */
  40221. RibbonGeometry.prototype._regenerateVertexData = function () {
  40222. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40223. };
  40224. RibbonGeometry.prototype.copy = function (id) {
  40225. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40226. };
  40227. return RibbonGeometry;
  40228. }(_PrimitiveGeometry));
  40229. BABYLON.RibbonGeometry = RibbonGeometry;
  40230. /**
  40231. * Creates a box geometry
  40232. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40233. */
  40234. var BoxGeometry = /** @class */ (function (_super) {
  40235. __extends(BoxGeometry, _super);
  40236. /**
  40237. * Creates a box geometry
  40238. * @param id defines the unique ID of the geometry
  40239. * @param scene defines the hosting scene
  40240. * @param size defines the zise of the box (width, height and depth are the same)
  40241. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40242. * @param mesh defines the hosting mesh (can be null)
  40243. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40244. */
  40245. function BoxGeometry(id, scene,
  40246. /**
  40247. * Defines the zise of the box (width, height and depth are the same)
  40248. */
  40249. size, canBeRegenerated, mesh,
  40250. /**
  40251. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40252. */
  40253. side) {
  40254. if (mesh === void 0) { mesh = null; }
  40255. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40256. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40257. _this.size = size;
  40258. _this.side = side;
  40259. return _this;
  40260. }
  40261. /** @hidden */
  40262. BoxGeometry.prototype._regenerateVertexData = function () {
  40263. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40264. };
  40265. BoxGeometry.prototype.copy = function (id) {
  40266. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40267. };
  40268. BoxGeometry.prototype.serialize = function () {
  40269. var serializationObject = _super.prototype.serialize.call(this);
  40270. serializationObject.size = this.size;
  40271. return serializationObject;
  40272. };
  40273. BoxGeometry.Parse = function (parsedBox, scene) {
  40274. if (scene.getGeometryByID(parsedBox.id)) {
  40275. return null; // null since geometry could be something else than a box...
  40276. }
  40277. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40278. if (BABYLON.Tags) {
  40279. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40280. }
  40281. scene.pushGeometry(box, true);
  40282. return box;
  40283. };
  40284. return BoxGeometry;
  40285. }(_PrimitiveGeometry));
  40286. BABYLON.BoxGeometry = BoxGeometry;
  40287. /**
  40288. * Creates a sphere geometry
  40289. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40290. */
  40291. var SphereGeometry = /** @class */ (function (_super) {
  40292. __extends(SphereGeometry, _super);
  40293. /**
  40294. * Create a new sphere geometry
  40295. * @param id defines the unique ID of the geometry
  40296. * @param scene defines the hosting scene
  40297. * @param segments defines the number of segments to use to create the sphere
  40298. * @param diameter defines the diameter of the sphere
  40299. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40300. * @param mesh defines the hosting mesh (can be null)
  40301. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40302. */
  40303. function SphereGeometry(id, scene,
  40304. /**
  40305. * Defines the number of segments to use to create the sphere
  40306. */
  40307. segments,
  40308. /**
  40309. * Defines the diameter of the sphere
  40310. */
  40311. diameter, canBeRegenerated, mesh,
  40312. /**
  40313. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40314. */
  40315. side) {
  40316. if (mesh === void 0) { mesh = null; }
  40317. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40318. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40319. _this.segments = segments;
  40320. _this.diameter = diameter;
  40321. _this.side = side;
  40322. return _this;
  40323. }
  40324. /** @hidden */
  40325. SphereGeometry.prototype._regenerateVertexData = function () {
  40326. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40327. };
  40328. SphereGeometry.prototype.copy = function (id) {
  40329. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40330. };
  40331. SphereGeometry.prototype.serialize = function () {
  40332. var serializationObject = _super.prototype.serialize.call(this);
  40333. serializationObject.segments = this.segments;
  40334. serializationObject.diameter = this.diameter;
  40335. return serializationObject;
  40336. };
  40337. SphereGeometry.Parse = function (parsedSphere, scene) {
  40338. if (scene.getGeometryByID(parsedSphere.id)) {
  40339. return null; // null since geometry could be something else than a sphere...
  40340. }
  40341. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40342. if (BABYLON.Tags) {
  40343. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40344. }
  40345. scene.pushGeometry(sphere, true);
  40346. return sphere;
  40347. };
  40348. return SphereGeometry;
  40349. }(_PrimitiveGeometry));
  40350. BABYLON.SphereGeometry = SphereGeometry;
  40351. /**
  40352. * Creates a disc geometry
  40353. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40354. */
  40355. var DiscGeometry = /** @class */ (function (_super) {
  40356. __extends(DiscGeometry, _super);
  40357. /**
  40358. * Creates a new disc geometry
  40359. * @param id defines the unique ID of the geometry
  40360. * @param scene defines the hosting scene
  40361. * @param radius defines the radius of the disc
  40362. * @param tessellation defines the tesselation factor to apply to the disc
  40363. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40364. * @param mesh defines the hosting mesh (can be null)
  40365. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40366. */
  40367. function DiscGeometry(id, scene,
  40368. /**
  40369. * Defines the radius of the disc
  40370. */
  40371. radius,
  40372. /**
  40373. * Defines the tesselation factor to apply to the disc
  40374. */
  40375. tessellation, canBeRegenerated, mesh,
  40376. /**
  40377. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40378. */
  40379. side) {
  40380. if (mesh === void 0) { mesh = null; }
  40381. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40382. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40383. _this.radius = radius;
  40384. _this.tessellation = tessellation;
  40385. _this.side = side;
  40386. return _this;
  40387. }
  40388. /** @hidden */
  40389. DiscGeometry.prototype._regenerateVertexData = function () {
  40390. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40391. };
  40392. DiscGeometry.prototype.copy = function (id) {
  40393. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40394. };
  40395. return DiscGeometry;
  40396. }(_PrimitiveGeometry));
  40397. BABYLON.DiscGeometry = DiscGeometry;
  40398. /**
  40399. * Creates a new cylinder geometry
  40400. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40401. */
  40402. var CylinderGeometry = /** @class */ (function (_super) {
  40403. __extends(CylinderGeometry, _super);
  40404. /**
  40405. * Creates a new cylinder geometry
  40406. * @param id defines the unique ID of the geometry
  40407. * @param scene defines the hosting scene
  40408. * @param height defines the height of the cylinder
  40409. * @param diameterTop defines the diameter of the cylinder's top cap
  40410. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40411. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40412. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40413. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40414. * @param mesh defines the hosting mesh (can be null)
  40415. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40416. */
  40417. function CylinderGeometry(id, scene,
  40418. /**
  40419. * Defines the height of the cylinder
  40420. */
  40421. height,
  40422. /**
  40423. * Defines the diameter of the cylinder's top cap
  40424. */
  40425. diameterTop,
  40426. /**
  40427. * Defines the diameter of the cylinder's bottom cap
  40428. */
  40429. diameterBottom,
  40430. /**
  40431. * Defines the tessellation factor to apply to the cylinder
  40432. */
  40433. tessellation,
  40434. /**
  40435. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40436. */
  40437. subdivisions, canBeRegenerated, mesh,
  40438. /**
  40439. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40440. */
  40441. side) {
  40442. if (subdivisions === void 0) { subdivisions = 1; }
  40443. if (mesh === void 0) { mesh = null; }
  40444. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40445. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40446. _this.height = height;
  40447. _this.diameterTop = diameterTop;
  40448. _this.diameterBottom = diameterBottom;
  40449. _this.tessellation = tessellation;
  40450. _this.subdivisions = subdivisions;
  40451. _this.side = side;
  40452. return _this;
  40453. }
  40454. /** @hidden */
  40455. CylinderGeometry.prototype._regenerateVertexData = function () {
  40456. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40457. };
  40458. CylinderGeometry.prototype.copy = function (id) {
  40459. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40460. };
  40461. CylinderGeometry.prototype.serialize = function () {
  40462. var serializationObject = _super.prototype.serialize.call(this);
  40463. serializationObject.height = this.height;
  40464. serializationObject.diameterTop = this.diameterTop;
  40465. serializationObject.diameterBottom = this.diameterBottom;
  40466. serializationObject.tessellation = this.tessellation;
  40467. return serializationObject;
  40468. };
  40469. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40470. if (scene.getGeometryByID(parsedCylinder.id)) {
  40471. return null; // null since geometry could be something else than a cylinder...
  40472. }
  40473. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40474. if (BABYLON.Tags) {
  40475. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40476. }
  40477. scene.pushGeometry(cylinder, true);
  40478. return cylinder;
  40479. };
  40480. return CylinderGeometry;
  40481. }(_PrimitiveGeometry));
  40482. BABYLON.CylinderGeometry = CylinderGeometry;
  40483. /**
  40484. * Creates a new torus geometry
  40485. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40486. */
  40487. var TorusGeometry = /** @class */ (function (_super) {
  40488. __extends(TorusGeometry, _super);
  40489. /**
  40490. * Creates a new torus geometry
  40491. * @param id defines the unique ID of the geometry
  40492. * @param scene defines the hosting scene
  40493. * @param diameter defines the diameter of the torus
  40494. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40495. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40496. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40497. * @param mesh defines the hosting mesh (can be null)
  40498. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40499. */
  40500. function TorusGeometry(id, scene,
  40501. /**
  40502. * Defines the diameter of the torus
  40503. */
  40504. diameter,
  40505. /**
  40506. * Defines the thickness of the torus (ie. internal diameter)
  40507. */
  40508. thickness,
  40509. /**
  40510. * Defines the tesselation factor to apply to the torus
  40511. */
  40512. tessellation, canBeRegenerated, mesh,
  40513. /**
  40514. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40515. */
  40516. side) {
  40517. if (mesh === void 0) { mesh = null; }
  40518. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40519. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40520. _this.diameter = diameter;
  40521. _this.thickness = thickness;
  40522. _this.tessellation = tessellation;
  40523. _this.side = side;
  40524. return _this;
  40525. }
  40526. /** @hidden */
  40527. TorusGeometry.prototype._regenerateVertexData = function () {
  40528. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40529. };
  40530. TorusGeometry.prototype.copy = function (id) {
  40531. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40532. };
  40533. TorusGeometry.prototype.serialize = function () {
  40534. var serializationObject = _super.prototype.serialize.call(this);
  40535. serializationObject.diameter = this.diameter;
  40536. serializationObject.thickness = this.thickness;
  40537. serializationObject.tessellation = this.tessellation;
  40538. return serializationObject;
  40539. };
  40540. TorusGeometry.Parse = function (parsedTorus, scene) {
  40541. if (scene.getGeometryByID(parsedTorus.id)) {
  40542. return null; // null since geometry could be something else than a torus...
  40543. }
  40544. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40545. if (BABYLON.Tags) {
  40546. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40547. }
  40548. scene.pushGeometry(torus, true);
  40549. return torus;
  40550. };
  40551. return TorusGeometry;
  40552. }(_PrimitiveGeometry));
  40553. BABYLON.TorusGeometry = TorusGeometry;
  40554. /**
  40555. * Creates a new ground geometry
  40556. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40557. */
  40558. var GroundGeometry = /** @class */ (function (_super) {
  40559. __extends(GroundGeometry, _super);
  40560. /**
  40561. * Creates a new ground geometry
  40562. * @param id defines the unique ID of the geometry
  40563. * @param scene defines the hosting scene
  40564. * @param width defines the width of the ground
  40565. * @param height defines the height of the ground
  40566. * @param subdivisions defines the subdivisions to apply to the ground
  40567. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40568. * @param mesh defines the hosting mesh (can be null)
  40569. */
  40570. function GroundGeometry(id, scene,
  40571. /**
  40572. * Defines the width of the ground
  40573. */
  40574. width,
  40575. /**
  40576. * Defines the height of the ground
  40577. */
  40578. height,
  40579. /**
  40580. * Defines the subdivisions to apply to the ground
  40581. */
  40582. subdivisions, canBeRegenerated, mesh) {
  40583. if (mesh === void 0) { mesh = null; }
  40584. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40585. _this.width = width;
  40586. _this.height = height;
  40587. _this.subdivisions = subdivisions;
  40588. return _this;
  40589. }
  40590. /** @hidden */
  40591. GroundGeometry.prototype._regenerateVertexData = function () {
  40592. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40593. };
  40594. GroundGeometry.prototype.copy = function (id) {
  40595. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40596. };
  40597. GroundGeometry.prototype.serialize = function () {
  40598. var serializationObject = _super.prototype.serialize.call(this);
  40599. serializationObject.width = this.width;
  40600. serializationObject.height = this.height;
  40601. serializationObject.subdivisions = this.subdivisions;
  40602. return serializationObject;
  40603. };
  40604. GroundGeometry.Parse = function (parsedGround, scene) {
  40605. if (scene.getGeometryByID(parsedGround.id)) {
  40606. return null; // null since geometry could be something else than a ground...
  40607. }
  40608. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40609. if (BABYLON.Tags) {
  40610. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40611. }
  40612. scene.pushGeometry(ground, true);
  40613. return ground;
  40614. };
  40615. return GroundGeometry;
  40616. }(_PrimitiveGeometry));
  40617. BABYLON.GroundGeometry = GroundGeometry;
  40618. /**
  40619. * Creates a tiled ground geometry
  40620. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40621. */
  40622. var TiledGroundGeometry = /** @class */ (function (_super) {
  40623. __extends(TiledGroundGeometry, _super);
  40624. /**
  40625. * Creates a tiled ground geometry
  40626. * @param id defines the unique ID of the geometry
  40627. * @param scene defines the hosting scene
  40628. * @param xmin defines the minimum value on X axis
  40629. * @param zmin defines the minimum value on Z axis
  40630. * @param xmax defines the maximum value on X axis
  40631. * @param zmax defines the maximum value on Z axis
  40632. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40633. * @param precision defines the precision to use when computing the tiles
  40634. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40635. * @param mesh defines the hosting mesh (can be null)
  40636. */
  40637. function TiledGroundGeometry(id, scene,
  40638. /**
  40639. * Defines the minimum value on X axis
  40640. */
  40641. xmin,
  40642. /**
  40643. * Defines the minimum value on Z axis
  40644. */
  40645. zmin,
  40646. /**
  40647. * Defines the maximum value on X axis
  40648. */
  40649. xmax,
  40650. /**
  40651. * Defines the maximum value on Z axis
  40652. */
  40653. zmax,
  40654. /**
  40655. * Defines the subdivisions to apply to the ground
  40656. */
  40657. subdivisions,
  40658. /**
  40659. * Defines the precision to use when computing the tiles
  40660. */
  40661. precision, canBeRegenerated, mesh) {
  40662. if (mesh === void 0) { mesh = null; }
  40663. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40664. _this.xmin = xmin;
  40665. _this.zmin = zmin;
  40666. _this.xmax = xmax;
  40667. _this.zmax = zmax;
  40668. _this.subdivisions = subdivisions;
  40669. _this.precision = precision;
  40670. return _this;
  40671. }
  40672. /** @hidden */
  40673. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40674. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40675. };
  40676. TiledGroundGeometry.prototype.copy = function (id) {
  40677. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40678. };
  40679. return TiledGroundGeometry;
  40680. }(_PrimitiveGeometry));
  40681. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40682. /**
  40683. * Creates a plane geometry
  40684. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40685. */
  40686. var PlaneGeometry = /** @class */ (function (_super) {
  40687. __extends(PlaneGeometry, _super);
  40688. /**
  40689. * Creates a plane geometry
  40690. * @param id defines the unique ID of the geometry
  40691. * @param scene defines the hosting scene
  40692. * @param size defines the size of the plane (width === height)
  40693. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40694. * @param mesh defines the hosting mesh (can be null)
  40695. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40696. */
  40697. function PlaneGeometry(id, scene,
  40698. /**
  40699. * Defines the size of the plane (width === height)
  40700. */
  40701. size, canBeRegenerated, mesh,
  40702. /**
  40703. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40704. */
  40705. side) {
  40706. if (mesh === void 0) { mesh = null; }
  40707. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40708. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40709. _this.size = size;
  40710. _this.side = side;
  40711. return _this;
  40712. }
  40713. /** @hidden */
  40714. PlaneGeometry.prototype._regenerateVertexData = function () {
  40715. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40716. };
  40717. PlaneGeometry.prototype.copy = function (id) {
  40718. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40719. };
  40720. PlaneGeometry.prototype.serialize = function () {
  40721. var serializationObject = _super.prototype.serialize.call(this);
  40722. serializationObject.size = this.size;
  40723. return serializationObject;
  40724. };
  40725. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40726. if (scene.getGeometryByID(parsedPlane.id)) {
  40727. return null; // null since geometry could be something else than a ground...
  40728. }
  40729. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40730. if (BABYLON.Tags) {
  40731. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40732. }
  40733. scene.pushGeometry(plane, true);
  40734. return plane;
  40735. };
  40736. return PlaneGeometry;
  40737. }(_PrimitiveGeometry));
  40738. BABYLON.PlaneGeometry = PlaneGeometry;
  40739. /**
  40740. * Creates a torus knot geometry
  40741. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40742. */
  40743. var TorusKnotGeometry = /** @class */ (function (_super) {
  40744. __extends(TorusKnotGeometry, _super);
  40745. /**
  40746. * Creates a torus knot geometry
  40747. * @param id defines the unique ID of the geometry
  40748. * @param scene defines the hosting scene
  40749. * @param radius defines the radius of the torus knot
  40750. * @param tube defines the thickness of the torus knot tube
  40751. * @param radialSegments defines the number of radial segments
  40752. * @param tubularSegments defines the number of tubular segments
  40753. * @param p defines the first number of windings
  40754. * @param q defines the second number of windings
  40755. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40756. * @param mesh defines the hosting mesh (can be null)
  40757. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40758. */
  40759. function TorusKnotGeometry(id, scene,
  40760. /**
  40761. * Defines the radius of the torus knot
  40762. */
  40763. radius,
  40764. /**
  40765. * Defines the thickness of the torus knot tube
  40766. */
  40767. tube,
  40768. /**
  40769. * Defines the number of radial segments
  40770. */
  40771. radialSegments,
  40772. /**
  40773. * Defines the number of tubular segments
  40774. */
  40775. tubularSegments,
  40776. /**
  40777. * Defines the first number of windings
  40778. */
  40779. p,
  40780. /**
  40781. * Defines the second number of windings
  40782. */
  40783. q, canBeRegenerated, mesh,
  40784. /**
  40785. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40786. */
  40787. side) {
  40788. if (mesh === void 0) { mesh = null; }
  40789. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40790. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40791. _this.radius = radius;
  40792. _this.tube = tube;
  40793. _this.radialSegments = radialSegments;
  40794. _this.tubularSegments = tubularSegments;
  40795. _this.p = p;
  40796. _this.q = q;
  40797. _this.side = side;
  40798. return _this;
  40799. }
  40800. /** @hidden */
  40801. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40802. 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 });
  40803. };
  40804. TorusKnotGeometry.prototype.copy = function (id) {
  40805. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40806. };
  40807. TorusKnotGeometry.prototype.serialize = function () {
  40808. var serializationObject = _super.prototype.serialize.call(this);
  40809. serializationObject.radius = this.radius;
  40810. serializationObject.tube = this.tube;
  40811. serializationObject.radialSegments = this.radialSegments;
  40812. serializationObject.tubularSegments = this.tubularSegments;
  40813. serializationObject.p = this.p;
  40814. serializationObject.q = this.q;
  40815. return serializationObject;
  40816. };
  40817. ;
  40818. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40819. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40820. return null; // null since geometry could be something else than a ground...
  40821. }
  40822. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40823. if (BABYLON.Tags) {
  40824. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40825. }
  40826. scene.pushGeometry(torusKnot, true);
  40827. return torusKnot;
  40828. };
  40829. return TorusKnotGeometry;
  40830. }(_PrimitiveGeometry));
  40831. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40832. //}
  40833. })(BABYLON || (BABYLON = {}));
  40834. //# sourceMappingURL=babylon.geometry.js.map
  40835. var BABYLON;
  40836. (function (BABYLON) {
  40837. /**
  40838. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40839. */
  40840. var PerformanceMonitor = /** @class */ (function () {
  40841. /**
  40842. * constructor
  40843. * @param frameSampleSize The number of samples required to saturate the sliding window
  40844. */
  40845. function PerformanceMonitor(frameSampleSize) {
  40846. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40847. this._enabled = true;
  40848. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40849. }
  40850. /**
  40851. * Samples current frame
  40852. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40853. */
  40854. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40855. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40856. if (!this._enabled)
  40857. return;
  40858. if (this._lastFrameTimeMs != null) {
  40859. var dt = timeMs - this._lastFrameTimeMs;
  40860. this._rollingFrameTime.add(dt);
  40861. }
  40862. this._lastFrameTimeMs = timeMs;
  40863. };
  40864. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40865. /**
  40866. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40867. * @return Average frame time in milliseconds
  40868. */
  40869. get: function () {
  40870. return this._rollingFrameTime.average;
  40871. },
  40872. enumerable: true,
  40873. configurable: true
  40874. });
  40875. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40876. /**
  40877. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40878. * @return Frame time variance in milliseconds squared
  40879. */
  40880. get: function () {
  40881. return this._rollingFrameTime.variance;
  40882. },
  40883. enumerable: true,
  40884. configurable: true
  40885. });
  40886. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40887. /**
  40888. * Returns the frame time of the most recent frame
  40889. * @return Frame time in milliseconds
  40890. */
  40891. get: function () {
  40892. return this._rollingFrameTime.history(0);
  40893. },
  40894. enumerable: true,
  40895. configurable: true
  40896. });
  40897. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40898. /**
  40899. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40900. * @return Framerate in frames per second
  40901. */
  40902. get: function () {
  40903. return 1000.0 / this._rollingFrameTime.average;
  40904. },
  40905. enumerable: true,
  40906. configurable: true
  40907. });
  40908. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40909. /**
  40910. * Returns the average framerate in frames per second using the most recent frame time
  40911. * @return Framerate in frames per second
  40912. */
  40913. get: function () {
  40914. var history = this._rollingFrameTime.history(0);
  40915. if (history === 0) {
  40916. return 0;
  40917. }
  40918. return 1000.0 / history;
  40919. },
  40920. enumerable: true,
  40921. configurable: true
  40922. });
  40923. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40924. /**
  40925. * Returns true if enough samples have been taken to completely fill the sliding window
  40926. * @return true if saturated
  40927. */
  40928. get: function () {
  40929. return this._rollingFrameTime.isSaturated();
  40930. },
  40931. enumerable: true,
  40932. configurable: true
  40933. });
  40934. /**
  40935. * Enables contributions to the sliding window sample set
  40936. */
  40937. PerformanceMonitor.prototype.enable = function () {
  40938. this._enabled = true;
  40939. };
  40940. /**
  40941. * Disables contributions to the sliding window sample set
  40942. * Samples will not be interpolated over the disabled period
  40943. */
  40944. PerformanceMonitor.prototype.disable = function () {
  40945. this._enabled = false;
  40946. //clear last sample to avoid interpolating over the disabled period when next enabled
  40947. this._lastFrameTimeMs = null;
  40948. };
  40949. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40950. /**
  40951. * Returns true if sampling is enabled
  40952. * @return true if enabled
  40953. */
  40954. get: function () {
  40955. return this._enabled;
  40956. },
  40957. enumerable: true,
  40958. configurable: true
  40959. });
  40960. /**
  40961. * Resets performance monitor
  40962. */
  40963. PerformanceMonitor.prototype.reset = function () {
  40964. //clear last sample to avoid interpolating over the disabled period when next enabled
  40965. this._lastFrameTimeMs = null;
  40966. //wipe record
  40967. this._rollingFrameTime.reset();
  40968. };
  40969. return PerformanceMonitor;
  40970. }());
  40971. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40972. /**
  40973. * RollingAverage
  40974. *
  40975. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40976. */
  40977. var RollingAverage = /** @class */ (function () {
  40978. /**
  40979. * constructor
  40980. * @param length The number of samples required to saturate the sliding window
  40981. */
  40982. function RollingAverage(length) {
  40983. this._samples = new Array(length);
  40984. this.reset();
  40985. }
  40986. /**
  40987. * Adds a sample to the sample set
  40988. * @param v The sample value
  40989. */
  40990. RollingAverage.prototype.add = function (v) {
  40991. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40992. var delta;
  40993. //we need to check if we've already wrapped round
  40994. if (this.isSaturated()) {
  40995. //remove bottom of stack from mean
  40996. var bottomValue = this._samples[this._pos];
  40997. delta = bottomValue - this.average;
  40998. this.average -= delta / (this._sampleCount - 1);
  40999. this._m2 -= delta * (bottomValue - this.average);
  41000. }
  41001. else {
  41002. this._sampleCount++;
  41003. }
  41004. //add new value to mean
  41005. delta = v - this.average;
  41006. this.average += delta / (this._sampleCount);
  41007. this._m2 += delta * (v - this.average);
  41008. //set the new variance
  41009. this.variance = this._m2 / (this._sampleCount - 1);
  41010. this._samples[this._pos] = v;
  41011. this._pos++;
  41012. this._pos %= this._samples.length; //positive wrap around
  41013. };
  41014. /**
  41015. * Returns previously added values or null if outside of history or outside the sliding window domain
  41016. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41017. * @return Value previously recorded with add() or null if outside of range
  41018. */
  41019. RollingAverage.prototype.history = function (i) {
  41020. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41021. return 0;
  41022. }
  41023. var i0 = this._wrapPosition(this._pos - 1.0);
  41024. return this._samples[this._wrapPosition(i0 - i)];
  41025. };
  41026. /**
  41027. * Returns true if enough samples have been taken to completely fill the sliding window
  41028. * @return true if sample-set saturated
  41029. */
  41030. RollingAverage.prototype.isSaturated = function () {
  41031. return this._sampleCount >= this._samples.length;
  41032. };
  41033. /**
  41034. * Resets the rolling average (equivalent to 0 samples taken so far)
  41035. */
  41036. RollingAverage.prototype.reset = function () {
  41037. this.average = 0;
  41038. this.variance = 0;
  41039. this._sampleCount = 0;
  41040. this._pos = 0;
  41041. this._m2 = 0;
  41042. };
  41043. /**
  41044. * Wraps a value around the sample range boundaries
  41045. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41046. * @return Wrapped position in sample range
  41047. */
  41048. RollingAverage.prototype._wrapPosition = function (i) {
  41049. var max = this._samples.length;
  41050. return ((i % max) + max) % max;
  41051. };
  41052. return RollingAverage;
  41053. }());
  41054. BABYLON.RollingAverage = RollingAverage;
  41055. })(BABYLON || (BABYLON = {}));
  41056. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41057. var BABYLON;
  41058. (function (BABYLON) {
  41059. /**
  41060. * "Static Class" containing the most commonly used helper while dealing with material for
  41061. * rendering purpose.
  41062. *
  41063. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41064. *
  41065. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41066. */
  41067. var MaterialHelper = /** @class */ (function () {
  41068. function MaterialHelper() {
  41069. }
  41070. /**
  41071. * Bind the current view position to an effect.
  41072. * @param effect The effect to be bound
  41073. * @param scene The scene the eyes position is used from
  41074. */
  41075. MaterialHelper.BindEyePosition = function (effect, scene) {
  41076. if (scene._forcedViewPosition) {
  41077. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41078. return;
  41079. }
  41080. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41081. };
  41082. /**
  41083. * Helps preparing the defines values about the UVs in used in the effect.
  41084. * UVs are shared as much as we can accross chanels in the shaders.
  41085. * @param texture The texture we are preparing the UVs for
  41086. * @param defines The defines to update
  41087. * @param key The chanel key "diffuse", "specular"... used in the shader
  41088. */
  41089. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41090. defines._needUVs = true;
  41091. defines[key] = true;
  41092. if (texture.getTextureMatrix().isIdentity(true)) {
  41093. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41094. if (texture.coordinatesIndex === 0) {
  41095. defines["MAINUV1"] = true;
  41096. }
  41097. else {
  41098. defines["MAINUV2"] = true;
  41099. }
  41100. }
  41101. else {
  41102. defines[key + "DIRECTUV"] = 0;
  41103. }
  41104. };
  41105. /**
  41106. * Binds a texture matrix value to its corrsponding uniform
  41107. * @param texture The texture to bind the matrix for
  41108. * @param uniformBuffer The uniform buffer receivin the data
  41109. * @param key The chanel key "diffuse", "specular"... used in the shader
  41110. */
  41111. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41112. var matrix = texture.getTextureMatrix();
  41113. if (!matrix.isIdentity(true)) {
  41114. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41115. }
  41116. };
  41117. /**
  41118. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41119. * @param mesh defines the current mesh
  41120. * @param scene defines the current scene
  41121. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41122. * @param pointsCloud defines if point cloud rendering has to be turned on
  41123. * @param fogEnabled defines if fog has to be turned on
  41124. * @param alphaTest defines if alpha testing has to be turned on
  41125. * @param defines defines the current list of defines
  41126. */
  41127. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41128. if (defines._areMiscDirty) {
  41129. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41130. defines["POINTSIZE"] = pointsCloud;
  41131. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41132. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41133. defines["ALPHATEST"] = alphaTest;
  41134. }
  41135. };
  41136. /**
  41137. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41138. * @param scene defines the current scene
  41139. * @param engine defines the current engine
  41140. * @param defines specifies the list of active defines
  41141. * @param useInstances defines if instances have to be turned on
  41142. * @param useClipPlane defines if clip plane have to be turned on
  41143. */
  41144. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41145. if (useClipPlane === void 0) { useClipPlane = null; }
  41146. var changed = false;
  41147. var useClipPlane1 = false;
  41148. var useClipPlane2 = false;
  41149. var useClipPlane3 = false;
  41150. var useClipPlane4 = false;
  41151. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41152. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41153. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41154. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41155. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41156. defines["CLIPPLANE"] = useClipPlane1;
  41157. changed = true;
  41158. }
  41159. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41160. defines["CLIPPLANE2"] = useClipPlane2;
  41161. changed = true;
  41162. }
  41163. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41164. defines["CLIPPLANE3"] = useClipPlane3;
  41165. changed = true;
  41166. }
  41167. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41168. defines["CLIPPLANE4"] = useClipPlane4;
  41169. changed = true;
  41170. }
  41171. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41172. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41173. changed = true;
  41174. }
  41175. if (defines["INSTANCES"] !== useInstances) {
  41176. defines["INSTANCES"] = useInstances;
  41177. changed = true;
  41178. }
  41179. if (changed) {
  41180. defines.markAsUnprocessed();
  41181. }
  41182. };
  41183. /**
  41184. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41185. * @param mesh The mesh containing the geometry data we will draw
  41186. * @param defines The defines to update
  41187. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41188. * @param useBones Precise whether bones should be used or not (override mesh info)
  41189. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41190. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41191. * @returns false if defines are considered not dirty and have not been checked
  41192. */
  41193. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41194. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41195. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41196. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41197. return false;
  41198. }
  41199. defines._normals = defines._needNormals;
  41200. defines._uvs = defines._needUVs;
  41201. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41202. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41203. defines["TANGENT"] = true;
  41204. }
  41205. if (defines._needUVs) {
  41206. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41207. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41208. }
  41209. else {
  41210. defines["UV1"] = false;
  41211. defines["UV2"] = false;
  41212. }
  41213. if (useVertexColor) {
  41214. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41215. defines["VERTEXCOLOR"] = hasVertexColors;
  41216. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41217. }
  41218. if (useBones) {
  41219. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41220. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41221. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41222. }
  41223. else {
  41224. defines["NUM_BONE_INFLUENCERS"] = 0;
  41225. defines["BonesPerMesh"] = 0;
  41226. }
  41227. }
  41228. if (useMorphTargets) {
  41229. var manager = mesh.morphTargetManager;
  41230. if (manager) {
  41231. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41232. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41233. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41234. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41235. }
  41236. else {
  41237. defines["MORPHTARGETS_TANGENT"] = false;
  41238. defines["MORPHTARGETS_NORMAL"] = false;
  41239. defines["MORPHTARGETS"] = false;
  41240. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41241. }
  41242. }
  41243. return true;
  41244. };
  41245. /**
  41246. * Prepares the defines related to the light information passed in parameter
  41247. * @param scene The scene we are intending to draw
  41248. * @param mesh The mesh the effect is compiling for
  41249. * @param defines The defines to update
  41250. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41251. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41252. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41253. * @returns true if normals will be required for the rest of the effect
  41254. */
  41255. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41256. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41257. if (disableLighting === void 0) { disableLighting = false; }
  41258. if (!defines._areLightsDirty) {
  41259. return defines._needNormals;
  41260. }
  41261. var lightIndex = 0;
  41262. var needNormals = false;
  41263. var needRebuild = false;
  41264. var lightmapMode = false;
  41265. var shadowEnabled = false;
  41266. var specularEnabled = false;
  41267. if (scene.lightsEnabled && !disableLighting) {
  41268. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41269. var light = _a[_i];
  41270. needNormals = true;
  41271. if (defines["LIGHT" + lightIndex] === undefined) {
  41272. needRebuild = true;
  41273. }
  41274. defines["LIGHT" + lightIndex] = true;
  41275. defines["SPOTLIGHT" + lightIndex] = false;
  41276. defines["HEMILIGHT" + lightIndex] = false;
  41277. defines["POINTLIGHT" + lightIndex] = false;
  41278. defines["DIRLIGHT" + lightIndex] = false;
  41279. light.prepareLightSpecificDefines(defines, lightIndex);
  41280. // FallOff.
  41281. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41282. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41283. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41284. switch (light.falloffType) {
  41285. case BABYLON.Light.FALLOFF_GLTF:
  41286. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41287. break;
  41288. case BABYLON.Light.FALLOFF_PHYSICAL:
  41289. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41290. break;
  41291. case BABYLON.Light.FALLOFF_STANDARD:
  41292. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41293. break;
  41294. }
  41295. // Specular
  41296. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41297. specularEnabled = true;
  41298. }
  41299. // Shadows
  41300. defines["SHADOW" + lightIndex] = false;
  41301. defines["SHADOWPCF" + lightIndex] = false;
  41302. defines["SHADOWPCSS" + lightIndex] = false;
  41303. defines["SHADOWPOISSON" + lightIndex] = false;
  41304. defines["SHADOWESM" + lightIndex] = false;
  41305. defines["SHADOWCUBE" + lightIndex] = false;
  41306. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41307. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41308. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41309. var shadowGenerator = light.getShadowGenerator();
  41310. if (shadowGenerator) {
  41311. var shadowMap = shadowGenerator.getShadowMap();
  41312. if (shadowMap) {
  41313. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41314. shadowEnabled = true;
  41315. shadowGenerator.prepareDefines(defines, lightIndex);
  41316. }
  41317. }
  41318. }
  41319. }
  41320. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41321. lightmapMode = true;
  41322. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41323. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41324. }
  41325. else {
  41326. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41327. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41328. }
  41329. lightIndex++;
  41330. if (lightIndex === maxSimultaneousLights)
  41331. break;
  41332. }
  41333. }
  41334. defines["SPECULARTERM"] = specularEnabled;
  41335. defines["SHADOWS"] = shadowEnabled;
  41336. // Resetting all other lights if any
  41337. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41338. if (defines["LIGHT" + index] !== undefined) {
  41339. defines["LIGHT" + index] = false;
  41340. defines["HEMILIGHT" + lightIndex] = false;
  41341. defines["POINTLIGHT" + lightIndex] = false;
  41342. defines["DIRLIGHT" + lightIndex] = false;
  41343. defines["SPOTLIGHT" + lightIndex] = false;
  41344. defines["SHADOW" + lightIndex] = false;
  41345. }
  41346. }
  41347. var caps = scene.getEngine().getCaps();
  41348. if (defines["SHADOWFLOAT"] === undefined) {
  41349. needRebuild = true;
  41350. }
  41351. defines["SHADOWFLOAT"] = shadowEnabled &&
  41352. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41353. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41354. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41355. if (needRebuild) {
  41356. defines.rebuild();
  41357. }
  41358. return needNormals;
  41359. };
  41360. /**
  41361. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41362. * that won t be acctive due to defines being turned off.
  41363. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41364. * @param samplersList The samplers list
  41365. * @param defines The defines helping in the list generation
  41366. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41367. */
  41368. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41369. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41370. var uniformsList;
  41371. var uniformBuffersList = null;
  41372. if (uniformsListOrOptions.uniformsNames) {
  41373. var options = uniformsListOrOptions;
  41374. uniformsList = options.uniformsNames;
  41375. uniformBuffersList = options.uniformBuffersNames;
  41376. samplersList = options.samplers;
  41377. defines = options.defines;
  41378. maxSimultaneousLights = options.maxSimultaneousLights;
  41379. }
  41380. else {
  41381. uniformsList = uniformsListOrOptions;
  41382. if (!samplersList) {
  41383. samplersList = [];
  41384. }
  41385. }
  41386. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41387. if (!defines["LIGHT" + lightIndex]) {
  41388. break;
  41389. }
  41390. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41391. if (uniformBuffersList) {
  41392. uniformBuffersList.push("Light" + lightIndex);
  41393. }
  41394. samplersList.push("shadowSampler" + lightIndex);
  41395. samplersList.push("depthSampler" + lightIndex);
  41396. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41397. samplersList.push("projectionLightSampler" + lightIndex);
  41398. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41399. }
  41400. }
  41401. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41402. uniformsList.push("morphTargetInfluences");
  41403. }
  41404. };
  41405. /**
  41406. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41407. * @param defines The defines to update while falling back
  41408. * @param fallbacks The authorized effect fallbacks
  41409. * @param maxSimultaneousLights The maximum number of lights allowed
  41410. * @param rank the current rank of the Effect
  41411. * @returns The newly affected rank
  41412. */
  41413. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41414. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41415. if (rank === void 0) { rank = 0; }
  41416. var lightFallbackRank = 0;
  41417. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41418. if (!defines["LIGHT" + lightIndex]) {
  41419. break;
  41420. }
  41421. if (lightIndex > 0) {
  41422. lightFallbackRank = rank + lightIndex;
  41423. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41424. }
  41425. if (!defines["SHADOWS"]) {
  41426. if (defines["SHADOW" + lightIndex]) {
  41427. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41428. }
  41429. if (defines["SHADOWPCF" + lightIndex]) {
  41430. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41431. }
  41432. if (defines["SHADOWPCSS" + lightIndex]) {
  41433. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41434. }
  41435. if (defines["SHADOWPOISSON" + lightIndex]) {
  41436. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41437. }
  41438. if (defines["SHADOWESM" + lightIndex]) {
  41439. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41440. }
  41441. }
  41442. }
  41443. return lightFallbackRank++;
  41444. };
  41445. /**
  41446. * Prepares the list of attributes required for morph targets according to the effect defines.
  41447. * @param attribs The current list of supported attribs
  41448. * @param mesh The mesh to prepare the morph targets attributes for
  41449. * @param defines The current Defines of the effect
  41450. */
  41451. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41452. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41453. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41454. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41455. var manager = mesh.morphTargetManager;
  41456. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41457. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41458. for (var index = 0; index < influencers; index++) {
  41459. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41460. if (normal) {
  41461. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41462. }
  41463. if (tangent) {
  41464. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41465. }
  41466. if (attribs.length > maxAttributesCount) {
  41467. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41468. }
  41469. }
  41470. }
  41471. };
  41472. /**
  41473. * Prepares the list of attributes required for bones according to the effect defines.
  41474. * @param attribs The current list of supported attribs
  41475. * @param mesh The mesh to prepare the bones attributes for
  41476. * @param defines The current Defines of the effect
  41477. * @param fallbacks The current efffect fallback strategy
  41478. */
  41479. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41480. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41481. fallbacks.addCPUSkinningFallback(0, mesh);
  41482. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41483. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41484. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41485. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41486. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41487. }
  41488. }
  41489. };
  41490. /**
  41491. * Prepares the list of attributes required for instances according to the effect defines.
  41492. * @param attribs The current list of supported attribs
  41493. * @param defines The current Defines of the effect
  41494. */
  41495. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41496. if (defines["INSTANCES"]) {
  41497. attribs.push("world0");
  41498. attribs.push("world1");
  41499. attribs.push("world2");
  41500. attribs.push("world3");
  41501. }
  41502. };
  41503. /**
  41504. * Binds the light shadow information to the effect for the given mesh.
  41505. * @param light The light containing the generator
  41506. * @param scene The scene the lights belongs to
  41507. * @param mesh The mesh we are binding the information to render
  41508. * @param lightIndex The light index in the effect used to render the mesh
  41509. * @param effect The effect we are binding the data to
  41510. */
  41511. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41512. if (light.shadowEnabled && mesh.receiveShadows) {
  41513. var shadowGenerator = light.getShadowGenerator();
  41514. if (shadowGenerator) {
  41515. shadowGenerator.bindShadowLight(lightIndex, effect);
  41516. }
  41517. }
  41518. };
  41519. /**
  41520. * Binds the light information to the effect.
  41521. * @param light The light containing the generator
  41522. * @param effect The effect we are binding the data to
  41523. * @param lightIndex The light index in the effect used to render
  41524. */
  41525. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41526. light.transferToEffect(effect, lightIndex + "");
  41527. };
  41528. /**
  41529. * Binds the lights information from the scene to the effect for the given mesh.
  41530. * @param scene The scene the lights belongs to
  41531. * @param mesh The mesh we are binding the information to render
  41532. * @param effect The effect we are binding the data to
  41533. * @param defines The generated defines for the effect
  41534. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41535. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41536. */
  41537. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41538. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41539. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41540. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41541. for (var i = 0; i < len; i++) {
  41542. var light = mesh._lightSources[i];
  41543. var iAsString = i.toString();
  41544. var scaledIntensity = light.getScaledIntensity();
  41545. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41546. MaterialHelper.BindLightProperties(light, effect, i);
  41547. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41548. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41549. if (defines["SPECULARTERM"]) {
  41550. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41551. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41552. }
  41553. // Shadows
  41554. if (scene.shadowsEnabled) {
  41555. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41556. }
  41557. light._uniformBuffer.update();
  41558. }
  41559. };
  41560. /**
  41561. * Binds the fog information from the scene to the effect for the given mesh.
  41562. * @param scene The scene the lights belongs to
  41563. * @param mesh The mesh we are binding the information to render
  41564. * @param effect The effect we are binding the data to
  41565. */
  41566. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41567. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41568. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41569. effect.setColor3("vFogColor", scene.fogColor);
  41570. }
  41571. };
  41572. /**
  41573. * Binds the bones information from the mesh to the effect.
  41574. * @param mesh The mesh we are binding the information to render
  41575. * @param effect The effect we are binding the data to
  41576. */
  41577. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41578. if (!effect || !mesh) {
  41579. return;
  41580. }
  41581. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41582. mesh.computeBonesUsingShaders = false;
  41583. }
  41584. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41585. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41586. if (matrices) {
  41587. effect.setMatrices("mBones", matrices);
  41588. }
  41589. }
  41590. };
  41591. /**
  41592. * Binds the morph targets information from the mesh to the effect.
  41593. * @param abstractMesh The mesh we are binding the information to render
  41594. * @param effect The effect we are binding the data to
  41595. */
  41596. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41597. var manager = abstractMesh.morphTargetManager;
  41598. if (!abstractMesh || !manager) {
  41599. return;
  41600. }
  41601. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41602. };
  41603. /**
  41604. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41605. * @param defines The generated defines used in the effect
  41606. * @param effect The effect we are binding the data to
  41607. * @param scene The scene we are willing to render with logarithmic scale for
  41608. */
  41609. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41610. if (defines["LOGARITHMICDEPTH"]) {
  41611. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41612. }
  41613. };
  41614. /**
  41615. * Binds the clip plane information from the scene to the effect.
  41616. * @param scene The scene the clip plane information are extracted from
  41617. * @param effect The effect we are binding the data to
  41618. */
  41619. MaterialHelper.BindClipPlane = function (effect, scene) {
  41620. if (scene.clipPlane) {
  41621. var clipPlane = scene.clipPlane;
  41622. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41623. }
  41624. if (scene.clipPlane2) {
  41625. var clipPlane = scene.clipPlane2;
  41626. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41627. }
  41628. if (scene.clipPlane3) {
  41629. var clipPlane = scene.clipPlane3;
  41630. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41631. }
  41632. if (scene.clipPlane4) {
  41633. var clipPlane = scene.clipPlane4;
  41634. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41635. }
  41636. };
  41637. return MaterialHelper;
  41638. }());
  41639. BABYLON.MaterialHelper = MaterialHelper;
  41640. })(BABYLON || (BABYLON = {}));
  41641. //# sourceMappingURL=babylon.materialHelper.js.map
  41642. var BABYLON;
  41643. (function (BABYLON) {
  41644. var PushMaterial = /** @class */ (function (_super) {
  41645. __extends(PushMaterial, _super);
  41646. function PushMaterial(name, scene) {
  41647. var _this = _super.call(this, name, scene) || this;
  41648. _this._normalMatrix = new BABYLON.Matrix();
  41649. _this.storeEffectOnSubMeshes = true;
  41650. return _this;
  41651. }
  41652. PushMaterial.prototype.getEffect = function () {
  41653. return this._activeEffect;
  41654. };
  41655. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41656. if (!mesh) {
  41657. return false;
  41658. }
  41659. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41660. return true;
  41661. }
  41662. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41663. };
  41664. /**
  41665. * Binds the given world matrix to the active effect
  41666. *
  41667. * @param world the matrix to bind
  41668. */
  41669. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41670. this._activeEffect.setMatrix("world", world);
  41671. };
  41672. /**
  41673. * Binds the given normal matrix to the active effect
  41674. *
  41675. * @param normalMatrix the matrix to bind
  41676. */
  41677. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41678. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41679. };
  41680. PushMaterial.prototype.bind = function (world, mesh) {
  41681. if (!mesh) {
  41682. return;
  41683. }
  41684. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41685. };
  41686. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41687. if (effect === void 0) { effect = null; }
  41688. _super.prototype._afterBind.call(this, mesh);
  41689. this.getScene()._cachedEffect = effect;
  41690. };
  41691. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41692. if (visibility === void 0) { visibility = 1; }
  41693. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41694. };
  41695. return PushMaterial;
  41696. }(BABYLON.Material));
  41697. BABYLON.PushMaterial = PushMaterial;
  41698. })(BABYLON || (BABYLON = {}));
  41699. //# sourceMappingURL=babylon.pushMaterial.js.map
  41700. var BABYLON;
  41701. (function (BABYLON) {
  41702. /** @hidden */
  41703. var StandardMaterialDefines = /** @class */ (function (_super) {
  41704. __extends(StandardMaterialDefines, _super);
  41705. function StandardMaterialDefines() {
  41706. var _this = _super.call(this) || this;
  41707. _this.MAINUV1 = false;
  41708. _this.MAINUV2 = false;
  41709. _this.DIFFUSE = false;
  41710. _this.DIFFUSEDIRECTUV = 0;
  41711. _this.AMBIENT = false;
  41712. _this.AMBIENTDIRECTUV = 0;
  41713. _this.OPACITY = false;
  41714. _this.OPACITYDIRECTUV = 0;
  41715. _this.OPACITYRGB = false;
  41716. _this.REFLECTION = false;
  41717. _this.EMISSIVE = false;
  41718. _this.EMISSIVEDIRECTUV = 0;
  41719. _this.SPECULAR = false;
  41720. _this.SPECULARDIRECTUV = 0;
  41721. _this.BUMP = false;
  41722. _this.BUMPDIRECTUV = 0;
  41723. _this.PARALLAX = false;
  41724. _this.PARALLAXOCCLUSION = false;
  41725. _this.SPECULAROVERALPHA = false;
  41726. _this.CLIPPLANE = false;
  41727. _this.CLIPPLANE2 = false;
  41728. _this.CLIPPLANE3 = false;
  41729. _this.CLIPPLANE4 = false;
  41730. _this.ALPHATEST = false;
  41731. _this.DEPTHPREPASS = false;
  41732. _this.ALPHAFROMDIFFUSE = false;
  41733. _this.POINTSIZE = false;
  41734. _this.FOG = false;
  41735. _this.SPECULARTERM = false;
  41736. _this.DIFFUSEFRESNEL = false;
  41737. _this.OPACITYFRESNEL = false;
  41738. _this.REFLECTIONFRESNEL = false;
  41739. _this.REFRACTIONFRESNEL = false;
  41740. _this.EMISSIVEFRESNEL = false;
  41741. _this.FRESNEL = false;
  41742. _this.NORMAL = false;
  41743. _this.UV1 = false;
  41744. _this.UV2 = false;
  41745. _this.VERTEXCOLOR = false;
  41746. _this.VERTEXALPHA = false;
  41747. _this.NUM_BONE_INFLUENCERS = 0;
  41748. _this.BonesPerMesh = 0;
  41749. _this.INSTANCES = false;
  41750. _this.GLOSSINESS = false;
  41751. _this.ROUGHNESS = false;
  41752. _this.EMISSIVEASILLUMINATION = false;
  41753. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41754. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41755. _this.LIGHTMAP = false;
  41756. _this.LIGHTMAPDIRECTUV = 0;
  41757. _this.OBJECTSPACE_NORMALMAP = false;
  41758. _this.USELIGHTMAPASSHADOWMAP = false;
  41759. _this.REFLECTIONMAP_3D = false;
  41760. _this.REFLECTIONMAP_SPHERICAL = false;
  41761. _this.REFLECTIONMAP_PLANAR = false;
  41762. _this.REFLECTIONMAP_CUBIC = false;
  41763. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41764. _this.REFLECTIONMAP_PROJECTION = false;
  41765. _this.REFLECTIONMAP_SKYBOX = false;
  41766. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41767. _this.REFLECTIONMAP_EXPLICIT = false;
  41768. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41769. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41770. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41771. _this.INVERTCUBICMAP = false;
  41772. _this.LOGARITHMICDEPTH = false;
  41773. _this.REFRACTION = false;
  41774. _this.REFRACTIONMAP_3D = false;
  41775. _this.REFLECTIONOVERALPHA = false;
  41776. _this.TWOSIDEDLIGHTING = false;
  41777. _this.SHADOWFLOAT = false;
  41778. _this.MORPHTARGETS = false;
  41779. _this.MORPHTARGETS_NORMAL = false;
  41780. _this.MORPHTARGETS_TANGENT = false;
  41781. _this.NUM_MORPH_INFLUENCERS = 0;
  41782. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41783. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41784. _this.IMAGEPROCESSING = false;
  41785. _this.VIGNETTE = false;
  41786. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41787. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41788. _this.TONEMAPPING = false;
  41789. _this.TONEMAPPING_ACES = false;
  41790. _this.CONTRAST = false;
  41791. _this.COLORCURVES = false;
  41792. _this.COLORGRADING = false;
  41793. _this.COLORGRADING3D = false;
  41794. _this.SAMPLER3DGREENDEPTH = false;
  41795. _this.SAMPLER3DBGRMAP = false;
  41796. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41797. /**
  41798. * If the reflection texture on this material is in linear color space
  41799. * @hidden
  41800. */
  41801. _this.IS_REFLECTION_LINEAR = false;
  41802. /**
  41803. * If the refraction texture on this material is in linear color space
  41804. * @hidden
  41805. */
  41806. _this.IS_REFRACTION_LINEAR = false;
  41807. _this.EXPOSURE = false;
  41808. _this.rebuild();
  41809. return _this;
  41810. }
  41811. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41812. var modes = [
  41813. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41814. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41815. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41816. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41817. ];
  41818. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41819. var mode = modes_1[_i];
  41820. this[mode] = (mode === modeToEnable);
  41821. }
  41822. };
  41823. return StandardMaterialDefines;
  41824. }(BABYLON.MaterialDefines));
  41825. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41826. var StandardMaterial = /** @class */ (function (_super) {
  41827. __extends(StandardMaterial, _super);
  41828. function StandardMaterial(name, scene) {
  41829. var _this = _super.call(this, name, scene) || this;
  41830. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41831. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41832. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41833. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41834. _this.specularPower = 64;
  41835. _this._useAlphaFromDiffuseTexture = false;
  41836. _this._useEmissiveAsIllumination = false;
  41837. _this._linkEmissiveWithDiffuse = false;
  41838. _this._useSpecularOverAlpha = false;
  41839. _this._useReflectionOverAlpha = false;
  41840. _this._disableLighting = false;
  41841. _this._useObjectSpaceNormalMap = false;
  41842. _this._useParallax = false;
  41843. _this._useParallaxOcclusion = false;
  41844. _this.parallaxScaleBias = 0.05;
  41845. _this._roughness = 0;
  41846. _this.indexOfRefraction = 0.98;
  41847. _this.invertRefractionY = true;
  41848. /**
  41849. * Defines the alpha limits in alpha test mode
  41850. */
  41851. _this.alphaCutOff = 0.4;
  41852. _this._useLightmapAsShadowmap = false;
  41853. _this._useReflectionFresnelFromSpecular = false;
  41854. _this._useGlossinessFromSpecularMapAlpha = false;
  41855. _this._maxSimultaneousLights = 4;
  41856. /**
  41857. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41858. */
  41859. _this._invertNormalMapX = false;
  41860. /**
  41861. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41862. */
  41863. _this._invertNormalMapY = false;
  41864. /**
  41865. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41866. */
  41867. _this._twoSidedLighting = false;
  41868. _this._renderTargets = new BABYLON.SmartArray(16);
  41869. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41870. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41871. // Setup the default processing configuration to the scene.
  41872. _this._attachImageProcessingConfiguration(null);
  41873. _this.getRenderTargetTextures = function () {
  41874. _this._renderTargets.reset();
  41875. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41876. _this._renderTargets.push(_this._reflectionTexture);
  41877. }
  41878. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41879. _this._renderTargets.push(_this._refractionTexture);
  41880. }
  41881. return _this._renderTargets;
  41882. };
  41883. return _this;
  41884. }
  41885. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41886. /**
  41887. * Gets the image processing configuration used either in this material.
  41888. */
  41889. get: function () {
  41890. return this._imageProcessingConfiguration;
  41891. },
  41892. /**
  41893. * Sets the Default image processing configuration used either in the this material.
  41894. *
  41895. * If sets to null, the scene one is in use.
  41896. */
  41897. set: function (value) {
  41898. this._attachImageProcessingConfiguration(value);
  41899. // Ensure the effect will be rebuilt.
  41900. this._markAllSubMeshesAsTexturesDirty();
  41901. },
  41902. enumerable: true,
  41903. configurable: true
  41904. });
  41905. /**
  41906. * Attaches a new image processing configuration to the Standard Material.
  41907. * @param configuration
  41908. */
  41909. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41910. var _this = this;
  41911. if (configuration === this._imageProcessingConfiguration) {
  41912. return;
  41913. }
  41914. // Detaches observer.
  41915. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41916. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41917. }
  41918. // Pick the scene configuration if needed.
  41919. if (!configuration) {
  41920. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41921. }
  41922. else {
  41923. this._imageProcessingConfiguration = configuration;
  41924. }
  41925. // Attaches observer.
  41926. if (this._imageProcessingConfiguration) {
  41927. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41928. _this._markAllSubMeshesAsImageProcessingDirty();
  41929. });
  41930. }
  41931. };
  41932. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41933. /**
  41934. * Gets wether the color curves effect is enabled.
  41935. */
  41936. get: function () {
  41937. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41938. },
  41939. /**
  41940. * Sets wether the color curves effect is enabled.
  41941. */
  41942. set: function (value) {
  41943. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41944. },
  41945. enumerable: true,
  41946. configurable: true
  41947. });
  41948. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41949. /**
  41950. * Gets wether the color grading effect is enabled.
  41951. */
  41952. get: function () {
  41953. return this.imageProcessingConfiguration.colorGradingEnabled;
  41954. },
  41955. /**
  41956. * Gets wether the color grading effect is enabled.
  41957. */
  41958. set: function (value) {
  41959. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41960. },
  41961. enumerable: true,
  41962. configurable: true
  41963. });
  41964. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41965. /**
  41966. * Gets wether tonemapping is enabled or not.
  41967. */
  41968. get: function () {
  41969. return this._imageProcessingConfiguration.toneMappingEnabled;
  41970. },
  41971. /**
  41972. * Sets wether tonemapping is enabled or not
  41973. */
  41974. set: function (value) {
  41975. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41976. },
  41977. enumerable: true,
  41978. configurable: true
  41979. });
  41980. ;
  41981. ;
  41982. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41983. /**
  41984. * The camera exposure used on this material.
  41985. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41986. * This corresponds to a photographic exposure.
  41987. */
  41988. get: function () {
  41989. return this._imageProcessingConfiguration.exposure;
  41990. },
  41991. /**
  41992. * The camera exposure used on this material.
  41993. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41994. * This corresponds to a photographic exposure.
  41995. */
  41996. set: function (value) {
  41997. this._imageProcessingConfiguration.exposure = value;
  41998. },
  41999. enumerable: true,
  42000. configurable: true
  42001. });
  42002. ;
  42003. ;
  42004. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42005. /**
  42006. * Gets The camera contrast used on this material.
  42007. */
  42008. get: function () {
  42009. return this._imageProcessingConfiguration.contrast;
  42010. },
  42011. /**
  42012. * Sets The camera contrast used on this material.
  42013. */
  42014. set: function (value) {
  42015. this._imageProcessingConfiguration.contrast = value;
  42016. },
  42017. enumerable: true,
  42018. configurable: true
  42019. });
  42020. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42021. /**
  42022. * Gets the Color Grading 2D Lookup Texture.
  42023. */
  42024. get: function () {
  42025. return this._imageProcessingConfiguration.colorGradingTexture;
  42026. },
  42027. /**
  42028. * Sets the Color Grading 2D Lookup Texture.
  42029. */
  42030. set: function (value) {
  42031. this._imageProcessingConfiguration.colorGradingTexture = value;
  42032. },
  42033. enumerable: true,
  42034. configurable: true
  42035. });
  42036. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42037. /**
  42038. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42039. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42040. * 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;
  42041. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42042. */
  42043. get: function () {
  42044. return this._imageProcessingConfiguration.colorCurves;
  42045. },
  42046. /**
  42047. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42048. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42049. * 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;
  42050. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42051. */
  42052. set: function (value) {
  42053. this._imageProcessingConfiguration.colorCurves = value;
  42054. },
  42055. enumerable: true,
  42056. configurable: true
  42057. });
  42058. StandardMaterial.prototype.getClassName = function () {
  42059. return "StandardMaterial";
  42060. };
  42061. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42062. get: function () {
  42063. return this._useLogarithmicDepth;
  42064. },
  42065. set: function (value) {
  42066. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42067. this._markAllSubMeshesAsMiscDirty();
  42068. },
  42069. enumerable: true,
  42070. configurable: true
  42071. });
  42072. StandardMaterial.prototype.needAlphaBlending = function () {
  42073. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42074. };
  42075. StandardMaterial.prototype.needAlphaTesting = function () {
  42076. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42077. };
  42078. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42079. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42080. };
  42081. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42082. return this._diffuseTexture;
  42083. };
  42084. /**
  42085. * Child classes can use it to update shaders
  42086. */
  42087. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42088. if (useInstances === void 0) { useInstances = false; }
  42089. if (subMesh.effect && this.isFrozen) {
  42090. if (this._wasPreviouslyReady) {
  42091. return true;
  42092. }
  42093. }
  42094. if (!subMesh._materialDefines) {
  42095. subMesh._materialDefines = new StandardMaterialDefines();
  42096. }
  42097. var scene = this.getScene();
  42098. var defines = subMesh._materialDefines;
  42099. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42100. if (defines._renderId === scene.getRenderId()) {
  42101. return true;
  42102. }
  42103. }
  42104. var engine = scene.getEngine();
  42105. // Lights
  42106. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42107. // Textures
  42108. if (defines._areTexturesDirty) {
  42109. defines._needUVs = false;
  42110. defines.MAINUV1 = false;
  42111. defines.MAINUV2 = false;
  42112. if (scene.texturesEnabled) {
  42113. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42114. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42115. return false;
  42116. }
  42117. else {
  42118. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42119. }
  42120. }
  42121. else {
  42122. defines.DIFFUSE = false;
  42123. }
  42124. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42125. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42126. return false;
  42127. }
  42128. else {
  42129. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42130. }
  42131. }
  42132. else {
  42133. defines.AMBIENT = false;
  42134. }
  42135. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42136. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42137. return false;
  42138. }
  42139. else {
  42140. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42141. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42142. }
  42143. }
  42144. else {
  42145. defines.OPACITY = false;
  42146. }
  42147. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42148. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42149. return false;
  42150. }
  42151. else {
  42152. defines._needNormals = true;
  42153. defines.REFLECTION = true;
  42154. defines.ROUGHNESS = (this._roughness > 0);
  42155. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42156. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42157. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42158. switch (this._reflectionTexture.coordinatesMode) {
  42159. case BABYLON.Texture.EXPLICIT_MODE:
  42160. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42161. break;
  42162. case BABYLON.Texture.PLANAR_MODE:
  42163. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42164. break;
  42165. case BABYLON.Texture.PROJECTION_MODE:
  42166. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42167. break;
  42168. case BABYLON.Texture.SKYBOX_MODE:
  42169. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42170. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42171. break;
  42172. case BABYLON.Texture.SPHERICAL_MODE:
  42173. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42174. break;
  42175. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42176. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42177. break;
  42178. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42179. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42180. break;
  42181. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42182. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42183. break;
  42184. case BABYLON.Texture.CUBIC_MODE:
  42185. case BABYLON.Texture.INVCUBIC_MODE:
  42186. default:
  42187. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42188. break;
  42189. }
  42190. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42191. }
  42192. }
  42193. else {
  42194. defines.REFLECTION = false;
  42195. }
  42196. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42197. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42198. return false;
  42199. }
  42200. else {
  42201. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42202. }
  42203. }
  42204. else {
  42205. defines.EMISSIVE = false;
  42206. }
  42207. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42208. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42209. return false;
  42210. }
  42211. else {
  42212. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42213. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42214. }
  42215. }
  42216. else {
  42217. defines.LIGHTMAP = false;
  42218. }
  42219. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42220. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42221. return false;
  42222. }
  42223. else {
  42224. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42225. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42226. }
  42227. }
  42228. else {
  42229. defines.SPECULAR = false;
  42230. }
  42231. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42232. // Bump texure can not be not blocking.
  42233. if (!this._bumpTexture.isReady()) {
  42234. return false;
  42235. }
  42236. else {
  42237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42238. defines.PARALLAX = this._useParallax;
  42239. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42240. }
  42241. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42242. }
  42243. else {
  42244. defines.BUMP = false;
  42245. }
  42246. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42247. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42248. return false;
  42249. }
  42250. else {
  42251. defines._needUVs = true;
  42252. defines.REFRACTION = true;
  42253. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42254. }
  42255. }
  42256. else {
  42257. defines.REFRACTION = false;
  42258. }
  42259. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42260. }
  42261. else {
  42262. defines.DIFFUSE = false;
  42263. defines.AMBIENT = false;
  42264. defines.OPACITY = false;
  42265. defines.REFLECTION = false;
  42266. defines.EMISSIVE = false;
  42267. defines.LIGHTMAP = false;
  42268. defines.BUMP = false;
  42269. defines.REFRACTION = false;
  42270. }
  42271. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42272. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42273. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42274. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42275. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42276. }
  42277. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42278. if (!this._imageProcessingConfiguration.isReady()) {
  42279. return false;
  42280. }
  42281. this._imageProcessingConfiguration.prepareDefines(defines);
  42282. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42283. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42284. }
  42285. if (defines._areFresnelDirty) {
  42286. if (StandardMaterial.FresnelEnabled) {
  42287. // Fresnel
  42288. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42289. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42290. this._reflectionFresnelParameters) {
  42291. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42292. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42293. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42294. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42295. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42296. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42297. defines._needNormals = true;
  42298. defines.FRESNEL = true;
  42299. }
  42300. }
  42301. else {
  42302. defines.FRESNEL = false;
  42303. }
  42304. }
  42305. // Misc.
  42306. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42307. // Attribs
  42308. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42309. // Values that need to be evaluated on every frame
  42310. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42311. // Get correct effect
  42312. if (defines.isDirty) {
  42313. defines.markAsProcessed();
  42314. scene.resetCachedMaterial();
  42315. // Fallbacks
  42316. var fallbacks = new BABYLON.EffectFallbacks();
  42317. if (defines.REFLECTION) {
  42318. fallbacks.addFallback(0, "REFLECTION");
  42319. }
  42320. if (defines.SPECULAR) {
  42321. fallbacks.addFallback(0, "SPECULAR");
  42322. }
  42323. if (defines.BUMP) {
  42324. fallbacks.addFallback(0, "BUMP");
  42325. }
  42326. if (defines.PARALLAX) {
  42327. fallbacks.addFallback(1, "PARALLAX");
  42328. }
  42329. if (defines.PARALLAXOCCLUSION) {
  42330. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42331. }
  42332. if (defines.SPECULAROVERALPHA) {
  42333. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42334. }
  42335. if (defines.FOG) {
  42336. fallbacks.addFallback(1, "FOG");
  42337. }
  42338. if (defines.POINTSIZE) {
  42339. fallbacks.addFallback(0, "POINTSIZE");
  42340. }
  42341. if (defines.LOGARITHMICDEPTH) {
  42342. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42343. }
  42344. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42345. if (defines.SPECULARTERM) {
  42346. fallbacks.addFallback(0, "SPECULARTERM");
  42347. }
  42348. if (defines.DIFFUSEFRESNEL) {
  42349. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42350. }
  42351. if (defines.OPACITYFRESNEL) {
  42352. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42353. }
  42354. if (defines.REFLECTIONFRESNEL) {
  42355. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42356. }
  42357. if (defines.EMISSIVEFRESNEL) {
  42358. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42359. }
  42360. if (defines.FRESNEL) {
  42361. fallbacks.addFallback(4, "FRESNEL");
  42362. }
  42363. //Attributes
  42364. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42365. if (defines.NORMAL) {
  42366. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42367. }
  42368. if (defines.UV1) {
  42369. attribs.push(BABYLON.VertexBuffer.UVKind);
  42370. }
  42371. if (defines.UV2) {
  42372. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42373. }
  42374. if (defines.VERTEXCOLOR) {
  42375. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42376. }
  42377. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42378. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42379. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42380. var shaderName = "default";
  42381. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42382. "vFogInfos", "vFogColor", "pointSize",
  42383. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42384. "mBones",
  42385. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42386. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42387. "vReflectionPosition", "vReflectionSize",
  42388. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42389. ];
  42390. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42391. var uniformBuffers = ["Material", "Scene"];
  42392. if (BABYLON.ImageProcessingConfiguration) {
  42393. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42394. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42395. }
  42396. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42397. uniformsNames: uniforms,
  42398. uniformBuffersNames: uniformBuffers,
  42399. samplers: samplers,
  42400. defines: defines,
  42401. maxSimultaneousLights: this._maxSimultaneousLights
  42402. });
  42403. if (this.customShaderNameResolve) {
  42404. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42405. }
  42406. var join = defines.toString();
  42407. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42408. attributes: attribs,
  42409. uniformsNames: uniforms,
  42410. uniformBuffersNames: uniformBuffers,
  42411. samplers: samplers,
  42412. defines: join,
  42413. fallbacks: fallbacks,
  42414. onCompiled: this.onCompiled,
  42415. onError: this.onError,
  42416. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42417. }, engine), defines);
  42418. this.buildUniformLayout();
  42419. }
  42420. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42421. return false;
  42422. }
  42423. defines._renderId = scene.getRenderId();
  42424. this._wasPreviouslyReady = true;
  42425. return true;
  42426. };
  42427. StandardMaterial.prototype.buildUniformLayout = function () {
  42428. // Order is important !
  42429. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42430. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42431. this._uniformBuffer.addUniform("opacityParts", 4);
  42432. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42433. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42434. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42435. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42436. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42437. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42438. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42439. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42440. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42441. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42442. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42443. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42444. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42445. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42446. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42447. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42448. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42449. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42450. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42451. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42452. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42453. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42454. this._uniformBuffer.addUniform("specularMatrix", 16);
  42455. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42456. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42457. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42458. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42459. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42460. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42461. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42462. this._uniformBuffer.addUniform("pointSize", 1);
  42463. this._uniformBuffer.create();
  42464. };
  42465. StandardMaterial.prototype.unbind = function () {
  42466. if (this._activeEffect) {
  42467. var needFlag = false;
  42468. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42469. this._activeEffect.setTexture("reflection2DSampler", null);
  42470. needFlag = true;
  42471. }
  42472. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42473. this._activeEffect.setTexture("refraction2DSampler", null);
  42474. needFlag = true;
  42475. }
  42476. if (needFlag) {
  42477. this._markAllSubMeshesAsTexturesDirty();
  42478. }
  42479. }
  42480. _super.prototype.unbind.call(this);
  42481. };
  42482. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42483. var scene = this.getScene();
  42484. var defines = subMesh._materialDefines;
  42485. if (!defines) {
  42486. return;
  42487. }
  42488. var effect = subMesh.effect;
  42489. if (!effect) {
  42490. return;
  42491. }
  42492. this._activeEffect = effect;
  42493. // Matrices
  42494. this.bindOnlyWorldMatrix(world);
  42495. // Normal Matrix
  42496. if (defines.OBJECTSPACE_NORMALMAP) {
  42497. world.toNormalMatrix(this._normalMatrix);
  42498. this.bindOnlyNormalMatrix(this._normalMatrix);
  42499. }
  42500. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42501. // Bones
  42502. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42503. if (mustRebind) {
  42504. this._uniformBuffer.bindToEffect(effect, "Material");
  42505. this.bindViewProjection(effect);
  42506. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42507. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42508. // Fresnel
  42509. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42510. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42511. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42512. }
  42513. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42514. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42515. }
  42516. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42517. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42518. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42519. }
  42520. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42521. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42522. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42523. }
  42524. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42525. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42526. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42527. }
  42528. }
  42529. // Textures
  42530. if (scene.texturesEnabled) {
  42531. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42532. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42533. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42534. if (this._diffuseTexture.hasAlpha) {
  42535. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42536. }
  42537. }
  42538. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42539. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42540. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42541. }
  42542. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42543. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42544. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42545. }
  42546. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42547. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42548. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42549. if (this._reflectionTexture.boundingBoxSize) {
  42550. var cubeTexture = this._reflectionTexture;
  42551. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42552. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42553. }
  42554. }
  42555. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42556. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42557. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42558. }
  42559. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42560. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42561. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42562. }
  42563. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42564. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42565. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42566. }
  42567. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42568. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42569. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42570. if (scene._mirroredCameraPosition) {
  42571. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42572. }
  42573. else {
  42574. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42575. }
  42576. }
  42577. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42578. var depth = 1.0;
  42579. if (!this._refractionTexture.isCube) {
  42580. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42581. if (this._refractionTexture.depth) {
  42582. depth = this._refractionTexture.depth;
  42583. }
  42584. }
  42585. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42586. }
  42587. }
  42588. // Point size
  42589. if (this.pointsCloud) {
  42590. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42591. }
  42592. if (defines.SPECULARTERM) {
  42593. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42594. }
  42595. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42596. // Diffuse
  42597. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42598. }
  42599. // Textures
  42600. if (scene.texturesEnabled) {
  42601. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42602. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42603. }
  42604. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42605. effect.setTexture("ambientSampler", this._ambientTexture);
  42606. }
  42607. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42608. effect.setTexture("opacitySampler", this._opacityTexture);
  42609. }
  42610. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42611. if (this._reflectionTexture.isCube) {
  42612. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42613. }
  42614. else {
  42615. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42616. }
  42617. }
  42618. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42619. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42620. }
  42621. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42622. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42623. }
  42624. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42625. effect.setTexture("specularSampler", this._specularTexture);
  42626. }
  42627. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42628. effect.setTexture("bumpSampler", this._bumpTexture);
  42629. }
  42630. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42631. var depth = 1.0;
  42632. if (this._refractionTexture.isCube) {
  42633. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42634. }
  42635. else {
  42636. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42637. }
  42638. }
  42639. }
  42640. // Clip plane
  42641. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42642. // Colors
  42643. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42644. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42645. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42646. }
  42647. if (mustRebind || !this.isFrozen) {
  42648. // Lights
  42649. if (scene.lightsEnabled && !this._disableLighting) {
  42650. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42651. }
  42652. // View
  42653. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42654. this.bindView(effect);
  42655. }
  42656. // Fog
  42657. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42658. // Morph targets
  42659. if (defines.NUM_MORPH_INFLUENCERS) {
  42660. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42661. }
  42662. // Log. depth
  42663. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42664. // image processing
  42665. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42666. this._imageProcessingConfiguration.bind(this._activeEffect);
  42667. }
  42668. }
  42669. this._uniformBuffer.update();
  42670. this._afterBind(mesh, this._activeEffect);
  42671. };
  42672. StandardMaterial.prototype.getAnimatables = function () {
  42673. var results = [];
  42674. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42675. results.push(this._diffuseTexture);
  42676. }
  42677. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42678. results.push(this._ambientTexture);
  42679. }
  42680. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42681. results.push(this._opacityTexture);
  42682. }
  42683. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42684. results.push(this._reflectionTexture);
  42685. }
  42686. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42687. results.push(this._emissiveTexture);
  42688. }
  42689. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42690. results.push(this._specularTexture);
  42691. }
  42692. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42693. results.push(this._bumpTexture);
  42694. }
  42695. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42696. results.push(this._lightmapTexture);
  42697. }
  42698. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42699. results.push(this._refractionTexture);
  42700. }
  42701. return results;
  42702. };
  42703. StandardMaterial.prototype.getActiveTextures = function () {
  42704. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42705. if (this._diffuseTexture) {
  42706. activeTextures.push(this._diffuseTexture);
  42707. }
  42708. if (this._ambientTexture) {
  42709. activeTextures.push(this._ambientTexture);
  42710. }
  42711. if (this._opacityTexture) {
  42712. activeTextures.push(this._opacityTexture);
  42713. }
  42714. if (this._reflectionTexture) {
  42715. activeTextures.push(this._reflectionTexture);
  42716. }
  42717. if (this._emissiveTexture) {
  42718. activeTextures.push(this._emissiveTexture);
  42719. }
  42720. if (this._specularTexture) {
  42721. activeTextures.push(this._specularTexture);
  42722. }
  42723. if (this._bumpTexture) {
  42724. activeTextures.push(this._bumpTexture);
  42725. }
  42726. if (this._lightmapTexture) {
  42727. activeTextures.push(this._lightmapTexture);
  42728. }
  42729. if (this._refractionTexture) {
  42730. activeTextures.push(this._refractionTexture);
  42731. }
  42732. return activeTextures;
  42733. };
  42734. StandardMaterial.prototype.hasTexture = function (texture) {
  42735. if (_super.prototype.hasTexture.call(this, texture)) {
  42736. return true;
  42737. }
  42738. if (this._diffuseTexture === texture) {
  42739. return true;
  42740. }
  42741. if (this._ambientTexture === texture) {
  42742. return true;
  42743. }
  42744. if (this._opacityTexture === texture) {
  42745. return true;
  42746. }
  42747. if (this._reflectionTexture === texture) {
  42748. return true;
  42749. }
  42750. if (this._emissiveTexture === texture) {
  42751. return true;
  42752. }
  42753. if (this._specularTexture === texture) {
  42754. return true;
  42755. }
  42756. if (this._bumpTexture === texture) {
  42757. return true;
  42758. }
  42759. if (this._lightmapTexture === texture) {
  42760. return true;
  42761. }
  42762. if (this._refractionTexture === texture) {
  42763. return true;
  42764. }
  42765. return false;
  42766. };
  42767. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42768. if (forceDisposeTextures) {
  42769. if (this._diffuseTexture) {
  42770. this._diffuseTexture.dispose();
  42771. }
  42772. if (this._ambientTexture) {
  42773. this._ambientTexture.dispose();
  42774. }
  42775. if (this._opacityTexture) {
  42776. this._opacityTexture.dispose();
  42777. }
  42778. if (this._reflectionTexture) {
  42779. this._reflectionTexture.dispose();
  42780. }
  42781. if (this._emissiveTexture) {
  42782. this._emissiveTexture.dispose();
  42783. }
  42784. if (this._specularTexture) {
  42785. this._specularTexture.dispose();
  42786. }
  42787. if (this._bumpTexture) {
  42788. this._bumpTexture.dispose();
  42789. }
  42790. if (this._lightmapTexture) {
  42791. this._lightmapTexture.dispose();
  42792. }
  42793. if (this._refractionTexture) {
  42794. this._refractionTexture.dispose();
  42795. }
  42796. }
  42797. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42798. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42799. }
  42800. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42801. };
  42802. StandardMaterial.prototype.clone = function (name) {
  42803. var _this = this;
  42804. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42805. result.name = name;
  42806. result.id = name;
  42807. return result;
  42808. };
  42809. StandardMaterial.prototype.serialize = function () {
  42810. return BABYLON.SerializationHelper.Serialize(this);
  42811. };
  42812. // Statics
  42813. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42814. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42815. };
  42816. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42817. get: function () {
  42818. return StandardMaterial._DiffuseTextureEnabled;
  42819. },
  42820. set: function (value) {
  42821. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42822. return;
  42823. }
  42824. StandardMaterial._DiffuseTextureEnabled = value;
  42825. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42826. },
  42827. enumerable: true,
  42828. configurable: true
  42829. });
  42830. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42831. get: function () {
  42832. return StandardMaterial._AmbientTextureEnabled;
  42833. },
  42834. set: function (value) {
  42835. if (StandardMaterial._AmbientTextureEnabled === value) {
  42836. return;
  42837. }
  42838. StandardMaterial._AmbientTextureEnabled = value;
  42839. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42840. },
  42841. enumerable: true,
  42842. configurable: true
  42843. });
  42844. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42845. get: function () {
  42846. return StandardMaterial._OpacityTextureEnabled;
  42847. },
  42848. set: function (value) {
  42849. if (StandardMaterial._OpacityTextureEnabled === value) {
  42850. return;
  42851. }
  42852. StandardMaterial._OpacityTextureEnabled = value;
  42853. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42854. },
  42855. enumerable: true,
  42856. configurable: true
  42857. });
  42858. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42859. get: function () {
  42860. return StandardMaterial._ReflectionTextureEnabled;
  42861. },
  42862. set: function (value) {
  42863. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42864. return;
  42865. }
  42866. StandardMaterial._ReflectionTextureEnabled = value;
  42867. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42868. },
  42869. enumerable: true,
  42870. configurable: true
  42871. });
  42872. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42873. get: function () {
  42874. return StandardMaterial._EmissiveTextureEnabled;
  42875. },
  42876. set: function (value) {
  42877. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42878. return;
  42879. }
  42880. StandardMaterial._EmissiveTextureEnabled = value;
  42881. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42882. },
  42883. enumerable: true,
  42884. configurable: true
  42885. });
  42886. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42887. get: function () {
  42888. return StandardMaterial._SpecularTextureEnabled;
  42889. },
  42890. set: function (value) {
  42891. if (StandardMaterial._SpecularTextureEnabled === value) {
  42892. return;
  42893. }
  42894. StandardMaterial._SpecularTextureEnabled = value;
  42895. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42896. },
  42897. enumerable: true,
  42898. configurable: true
  42899. });
  42900. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42901. get: function () {
  42902. return StandardMaterial._BumpTextureEnabled;
  42903. },
  42904. set: function (value) {
  42905. if (StandardMaterial._BumpTextureEnabled === value) {
  42906. return;
  42907. }
  42908. StandardMaterial._BumpTextureEnabled = value;
  42909. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42910. },
  42911. enumerable: true,
  42912. configurable: true
  42913. });
  42914. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42915. get: function () {
  42916. return StandardMaterial._LightmapTextureEnabled;
  42917. },
  42918. set: function (value) {
  42919. if (StandardMaterial._LightmapTextureEnabled === value) {
  42920. return;
  42921. }
  42922. StandardMaterial._LightmapTextureEnabled = value;
  42923. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42924. },
  42925. enumerable: true,
  42926. configurable: true
  42927. });
  42928. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42929. get: function () {
  42930. return StandardMaterial._RefractionTextureEnabled;
  42931. },
  42932. set: function (value) {
  42933. if (StandardMaterial._RefractionTextureEnabled === value) {
  42934. return;
  42935. }
  42936. StandardMaterial._RefractionTextureEnabled = value;
  42937. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42938. },
  42939. enumerable: true,
  42940. configurable: true
  42941. });
  42942. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42943. get: function () {
  42944. return StandardMaterial._ColorGradingTextureEnabled;
  42945. },
  42946. set: function (value) {
  42947. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42948. return;
  42949. }
  42950. StandardMaterial._ColorGradingTextureEnabled = value;
  42951. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42952. },
  42953. enumerable: true,
  42954. configurable: true
  42955. });
  42956. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42957. get: function () {
  42958. return StandardMaterial._FresnelEnabled;
  42959. },
  42960. set: function (value) {
  42961. if (StandardMaterial._FresnelEnabled === value) {
  42962. return;
  42963. }
  42964. StandardMaterial._FresnelEnabled = value;
  42965. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42966. },
  42967. enumerable: true,
  42968. configurable: true
  42969. });
  42970. // Flags used to enable or disable a type of texture for all Standard Materials
  42971. StandardMaterial._DiffuseTextureEnabled = true;
  42972. StandardMaterial._AmbientTextureEnabled = true;
  42973. StandardMaterial._OpacityTextureEnabled = true;
  42974. StandardMaterial._ReflectionTextureEnabled = true;
  42975. StandardMaterial._EmissiveTextureEnabled = true;
  42976. StandardMaterial._SpecularTextureEnabled = true;
  42977. StandardMaterial._BumpTextureEnabled = true;
  42978. StandardMaterial._LightmapTextureEnabled = true;
  42979. StandardMaterial._RefractionTextureEnabled = true;
  42980. StandardMaterial._ColorGradingTextureEnabled = true;
  42981. StandardMaterial._FresnelEnabled = true;
  42982. __decorate([
  42983. BABYLON.serializeAsTexture("diffuseTexture")
  42984. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42985. __decorate([
  42986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42987. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42988. __decorate([
  42989. BABYLON.serializeAsTexture("ambientTexture")
  42990. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42991. __decorate([
  42992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42993. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42994. __decorate([
  42995. BABYLON.serializeAsTexture("opacityTexture")
  42996. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42997. __decorate([
  42998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42999. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43000. __decorate([
  43001. BABYLON.serializeAsTexture("reflectionTexture")
  43002. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43003. __decorate([
  43004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43005. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43006. __decorate([
  43007. BABYLON.serializeAsTexture("emissiveTexture")
  43008. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43009. __decorate([
  43010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43011. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43012. __decorate([
  43013. BABYLON.serializeAsTexture("specularTexture")
  43014. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43015. __decorate([
  43016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43017. ], StandardMaterial.prototype, "specularTexture", void 0);
  43018. __decorate([
  43019. BABYLON.serializeAsTexture("bumpTexture")
  43020. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43021. __decorate([
  43022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43023. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43024. __decorate([
  43025. BABYLON.serializeAsTexture("lightmapTexture")
  43026. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43027. __decorate([
  43028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43029. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43030. __decorate([
  43031. BABYLON.serializeAsTexture("refractionTexture")
  43032. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43033. __decorate([
  43034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43035. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43036. __decorate([
  43037. BABYLON.serializeAsColor3("ambient")
  43038. ], StandardMaterial.prototype, "ambientColor", void 0);
  43039. __decorate([
  43040. BABYLON.serializeAsColor3("diffuse")
  43041. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43042. __decorate([
  43043. BABYLON.serializeAsColor3("specular")
  43044. ], StandardMaterial.prototype, "specularColor", void 0);
  43045. __decorate([
  43046. BABYLON.serializeAsColor3("emissive")
  43047. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43048. __decorate([
  43049. BABYLON.serialize()
  43050. ], StandardMaterial.prototype, "specularPower", void 0);
  43051. __decorate([
  43052. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43053. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43054. __decorate([
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43056. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43057. __decorate([
  43058. BABYLON.serialize("useEmissiveAsIllumination")
  43059. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43060. __decorate([
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43063. __decorate([
  43064. BABYLON.serialize("linkEmissiveWithDiffuse")
  43065. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43066. __decorate([
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43068. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43069. __decorate([
  43070. BABYLON.serialize("useSpecularOverAlpha")
  43071. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43072. __decorate([
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43075. __decorate([
  43076. BABYLON.serialize("useReflectionOverAlpha")
  43077. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43078. __decorate([
  43079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43080. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43081. __decorate([
  43082. BABYLON.serialize("disableLighting")
  43083. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43084. __decorate([
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43086. ], StandardMaterial.prototype, "disableLighting", void 0);
  43087. __decorate([
  43088. BABYLON.serialize("useObjectSpaceNormalMap")
  43089. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43090. __decorate([
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43092. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43093. __decorate([
  43094. BABYLON.serialize("useParallax")
  43095. ], StandardMaterial.prototype, "_useParallax", void 0);
  43096. __decorate([
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], StandardMaterial.prototype, "useParallax", void 0);
  43099. __decorate([
  43100. BABYLON.serialize("useParallaxOcclusion")
  43101. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43102. __decorate([
  43103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43104. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43105. __decorate([
  43106. BABYLON.serialize()
  43107. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43108. __decorate([
  43109. BABYLON.serialize("roughness")
  43110. ], StandardMaterial.prototype, "_roughness", void 0);
  43111. __decorate([
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], StandardMaterial.prototype, "roughness", void 0);
  43114. __decorate([
  43115. BABYLON.serialize()
  43116. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43117. __decorate([
  43118. BABYLON.serialize()
  43119. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43120. __decorate([
  43121. BABYLON.serialize()
  43122. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43123. __decorate([
  43124. BABYLON.serialize("useLightmapAsShadowmap")
  43125. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43126. __decorate([
  43127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43128. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43129. __decorate([
  43130. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43131. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43132. __decorate([
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43134. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43135. __decorate([
  43136. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43137. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43138. __decorate([
  43139. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43140. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43141. __decorate([
  43142. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43143. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43144. __decorate([
  43145. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43146. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43147. __decorate([
  43148. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43149. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43150. __decorate([
  43151. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43152. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43153. __decorate([
  43154. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43155. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43156. __decorate([
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43158. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43159. __decorate([
  43160. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43161. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43162. __decorate([
  43163. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43164. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43165. __decorate([
  43166. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43167. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43168. __decorate([
  43169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43170. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43171. __decorate([
  43172. BABYLON.serialize("maxSimultaneousLights")
  43173. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43174. __decorate([
  43175. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43176. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43177. __decorate([
  43178. BABYLON.serialize("invertNormalMapX")
  43179. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43180. __decorate([
  43181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43182. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43183. __decorate([
  43184. BABYLON.serialize("invertNormalMapY")
  43185. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43186. __decorate([
  43187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43188. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43189. __decorate([
  43190. BABYLON.serialize("twoSidedLighting")
  43191. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43192. __decorate([
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43195. __decorate([
  43196. BABYLON.serialize()
  43197. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43198. return StandardMaterial;
  43199. }(BABYLON.PushMaterial));
  43200. BABYLON.StandardMaterial = StandardMaterial;
  43201. })(BABYLON || (BABYLON = {}));
  43202. //# sourceMappingURL=babylon.standardMaterial.js.map
  43203. var BABYLON;
  43204. (function (BABYLON) {
  43205. /**
  43206. * Class representing spherical polynomial coefficients to the 3rd degree
  43207. */
  43208. var SphericalPolynomial = /** @class */ (function () {
  43209. function SphericalPolynomial() {
  43210. /**
  43211. * The x coefficients of the spherical polynomial
  43212. */
  43213. this.x = BABYLON.Vector3.Zero();
  43214. /**
  43215. * The y coefficients of the spherical polynomial
  43216. */
  43217. this.y = BABYLON.Vector3.Zero();
  43218. /**
  43219. * The z coefficients of the spherical polynomial
  43220. */
  43221. this.z = BABYLON.Vector3.Zero();
  43222. /**
  43223. * The xx coefficients of the spherical polynomial
  43224. */
  43225. this.xx = BABYLON.Vector3.Zero();
  43226. /**
  43227. * The yy coefficients of the spherical polynomial
  43228. */
  43229. this.yy = BABYLON.Vector3.Zero();
  43230. /**
  43231. * The zz coefficients of the spherical polynomial
  43232. */
  43233. this.zz = BABYLON.Vector3.Zero();
  43234. /**
  43235. * The xy coefficients of the spherical polynomial
  43236. */
  43237. this.xy = BABYLON.Vector3.Zero();
  43238. /**
  43239. * The yz coefficients of the spherical polynomial
  43240. */
  43241. this.yz = BABYLON.Vector3.Zero();
  43242. /**
  43243. * The zx coefficients of the spherical polynomial
  43244. */
  43245. this.zx = BABYLON.Vector3.Zero();
  43246. }
  43247. /**
  43248. * Adds an ambient color to the spherical polynomial
  43249. * @param color the color to add
  43250. */
  43251. SphericalPolynomial.prototype.addAmbient = function (color) {
  43252. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43253. this.xx = this.xx.add(colorVector);
  43254. this.yy = this.yy.add(colorVector);
  43255. this.zz = this.zz.add(colorVector);
  43256. };
  43257. /**
  43258. * Scales the spherical polynomial by the given amount
  43259. * @param scale the amount to scale
  43260. */
  43261. SphericalPolynomial.prototype.scale = function (scale) {
  43262. this.x = this.x.scale(scale);
  43263. this.y = this.y.scale(scale);
  43264. this.z = this.z.scale(scale);
  43265. this.xx = this.xx.scale(scale);
  43266. this.yy = this.yy.scale(scale);
  43267. this.zz = this.zz.scale(scale);
  43268. this.yz = this.yz.scale(scale);
  43269. this.zx = this.zx.scale(scale);
  43270. this.xy = this.xy.scale(scale);
  43271. };
  43272. /**
  43273. * Gets the spherical polynomial from harmonics
  43274. * @param harmonics the spherical harmonics
  43275. * @returns the spherical polynomial
  43276. */
  43277. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43278. var result = new SphericalPolynomial();
  43279. result.x = harmonics.l11.scale(1.02333);
  43280. result.y = harmonics.l1_1.scale(1.02333);
  43281. result.z = harmonics.l10.scale(1.02333);
  43282. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43283. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43284. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43285. result.yz = harmonics.l2_1.scale(0.858086);
  43286. result.zx = harmonics.l21.scale(0.858086);
  43287. result.xy = harmonics.l2_2.scale(0.858086);
  43288. result.scale(1.0 / Math.PI);
  43289. return result;
  43290. };
  43291. /**
  43292. * Constructs a spherical polynomial from an array.
  43293. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43294. * @returns the spherical polynomial
  43295. */
  43296. SphericalPolynomial.FromArray = function (data) {
  43297. var sp = new SphericalPolynomial();
  43298. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43299. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43300. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43301. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43302. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43303. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43304. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43305. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43306. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43307. return sp;
  43308. };
  43309. return SphericalPolynomial;
  43310. }());
  43311. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43312. /**
  43313. * Class representing spherical harmonics coefficients to the 3rd degree
  43314. */
  43315. var SphericalHarmonics = /** @class */ (function () {
  43316. function SphericalHarmonics() {
  43317. /**
  43318. * The l0,0 coefficients of the spherical harmonics
  43319. */
  43320. this.l00 = BABYLON.Vector3.Zero();
  43321. /**
  43322. * The l1,-1 coefficients of the spherical harmonics
  43323. */
  43324. this.l1_1 = BABYLON.Vector3.Zero();
  43325. /**
  43326. * The l1,0 coefficients of the spherical harmonics
  43327. */
  43328. this.l10 = BABYLON.Vector3.Zero();
  43329. /**
  43330. * The l1,1 coefficients of the spherical harmonics
  43331. */
  43332. this.l11 = BABYLON.Vector3.Zero();
  43333. /**
  43334. * The l2,-2 coefficients of the spherical harmonics
  43335. */
  43336. this.l2_2 = BABYLON.Vector3.Zero();
  43337. /**
  43338. * The l2,-1 coefficients of the spherical harmonics
  43339. */
  43340. this.l2_1 = BABYLON.Vector3.Zero();
  43341. /**
  43342. * The l2,0 coefficients of the spherical harmonics
  43343. */
  43344. this.l20 = BABYLON.Vector3.Zero();
  43345. /**
  43346. * The l2,1 coefficients of the spherical harmonics
  43347. */
  43348. this.l21 = BABYLON.Vector3.Zero();
  43349. /**
  43350. * The l2,2 coefficients of the spherical harmonics
  43351. */
  43352. this.lL22 = BABYLON.Vector3.Zero();
  43353. }
  43354. /**
  43355. * Adds a light to the spherical harmonics
  43356. * @param direction the direction of the light
  43357. * @param color the color of the light
  43358. * @param deltaSolidAngle the delta solid angle of the light
  43359. */
  43360. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43361. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43362. var c = colorVector.scale(deltaSolidAngle);
  43363. this.l00 = this.l00.add(c.scale(0.282095));
  43364. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43365. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43366. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43367. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43368. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43369. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43370. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43371. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43372. };
  43373. /**
  43374. * Scales the spherical harmonics by the given amount
  43375. * @param scale the amount to scale
  43376. */
  43377. SphericalHarmonics.prototype.scale = function (scale) {
  43378. this.l00 = this.l00.scale(scale);
  43379. this.l1_1 = this.l1_1.scale(scale);
  43380. this.l10 = this.l10.scale(scale);
  43381. this.l11 = this.l11.scale(scale);
  43382. this.l2_2 = this.l2_2.scale(scale);
  43383. this.l2_1 = this.l2_1.scale(scale);
  43384. this.l20 = this.l20.scale(scale);
  43385. this.l21 = this.l21.scale(scale);
  43386. this.lL22 = this.lL22.scale(scale);
  43387. };
  43388. /**
  43389. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43390. *
  43391. * ```
  43392. * E_lm = A_l * L_lm
  43393. * ```
  43394. *
  43395. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43396. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43397. * the scaling factors are given in equation 9.
  43398. */
  43399. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43400. // Constant (Band 0)
  43401. this.l00 = this.l00.scale(3.141593);
  43402. // Linear (Band 1)
  43403. this.l1_1 = this.l1_1.scale(2.094395);
  43404. this.l10 = this.l10.scale(2.094395);
  43405. this.l11 = this.l11.scale(2.094395);
  43406. // Quadratic (Band 2)
  43407. this.l2_2 = this.l2_2.scale(0.785398);
  43408. this.l2_1 = this.l2_1.scale(0.785398);
  43409. this.l20 = this.l20.scale(0.785398);
  43410. this.l21 = this.l21.scale(0.785398);
  43411. this.lL22 = this.lL22.scale(0.785398);
  43412. };
  43413. /**
  43414. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43415. *
  43416. * ```
  43417. * L = (1/pi) * E * rho
  43418. * ```
  43419. *
  43420. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43421. */
  43422. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43423. this.scale(1.0 / Math.PI);
  43424. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43425. // (The pixel shader must apply albedo after texture fetches, etc).
  43426. };
  43427. /**
  43428. * Gets the spherical harmonics from polynomial
  43429. * @param polynomial the spherical polynomial
  43430. * @returns the spherical harmonics
  43431. */
  43432. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43433. var result = new SphericalHarmonics();
  43434. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43435. result.l1_1 = polynomial.y.scale(0.977204);
  43436. result.l10 = polynomial.z.scale(0.977204);
  43437. result.l11 = polynomial.x.scale(0.977204);
  43438. result.l2_2 = polynomial.xy.scale(1.16538);
  43439. result.l2_1 = polynomial.yz.scale(1.16538);
  43440. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43441. result.l21 = polynomial.zx.scale(1.16538);
  43442. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43443. result.scale(Math.PI);
  43444. return result;
  43445. };
  43446. /**
  43447. * Constructs a spherical harmonics from an array.
  43448. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43449. * @returns the spherical harmonics
  43450. */
  43451. SphericalHarmonics.FromArray = function (data) {
  43452. var sh = new SphericalHarmonics();
  43453. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43454. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43455. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43456. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43457. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43458. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43459. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43460. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43461. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43462. return sh;
  43463. };
  43464. return SphericalHarmonics;
  43465. }());
  43466. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43467. })(BABYLON || (BABYLON = {}));
  43468. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43469. var BABYLON;
  43470. (function (BABYLON) {
  43471. var FileFaceOrientation = /** @class */ (function () {
  43472. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43473. this.name = name;
  43474. this.worldAxisForNormal = worldAxisForNormal;
  43475. this.worldAxisForFileX = worldAxisForFileX;
  43476. this.worldAxisForFileY = worldAxisForFileY;
  43477. }
  43478. return FileFaceOrientation;
  43479. }());
  43480. ;
  43481. /**
  43482. * Helper class dealing with the extraction of spherical polynomial dataArray
  43483. * from a cube map.
  43484. */
  43485. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43486. function CubeMapToSphericalPolynomialTools() {
  43487. }
  43488. /**
  43489. * Converts a texture to the according Spherical Polynomial data.
  43490. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43491. *
  43492. * @param texture The texture to extract the information from.
  43493. * @return The Spherical Polynomial data.
  43494. */
  43495. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43496. if (!texture.isCube) {
  43497. // Only supports cube Textures currently.
  43498. return null;
  43499. }
  43500. var size = texture.getSize().width;
  43501. var right = texture.readPixels(0);
  43502. var left = texture.readPixels(1);
  43503. var up;
  43504. var down;
  43505. if (texture.isRenderTarget) {
  43506. up = texture.readPixels(3);
  43507. down = texture.readPixels(2);
  43508. }
  43509. else {
  43510. up = texture.readPixels(2);
  43511. down = texture.readPixels(3);
  43512. }
  43513. var front = texture.readPixels(4);
  43514. var back = texture.readPixels(5);
  43515. var gammaSpace = texture.gammaSpace;
  43516. // Always read as RGBA.
  43517. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43518. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43519. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43520. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43521. }
  43522. var cubeInfo = {
  43523. size: size,
  43524. right: right,
  43525. left: left,
  43526. up: up,
  43527. down: down,
  43528. front: front,
  43529. back: back,
  43530. format: format,
  43531. type: type,
  43532. gammaSpace: gammaSpace,
  43533. };
  43534. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43535. };
  43536. /**
  43537. * Converts a cubemap to the according Spherical Polynomial data.
  43538. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43539. *
  43540. * @param cubeInfo The Cube map to extract the information from.
  43541. * @return The Spherical Polynomial data.
  43542. */
  43543. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43544. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43545. var totalSolidAngle = 0.0;
  43546. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43547. var du = 2.0 / cubeInfo.size;
  43548. var dv = du;
  43549. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43550. var minUV = du * 0.5 - 1.0;
  43551. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43552. var fileFace = this.FileFaces[faceIndex];
  43553. var dataArray = cubeInfo[fileFace.name];
  43554. var v = minUV;
  43555. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43556. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43557. // Because SP is still linear, so summation is fine in that basis.
  43558. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43559. for (var y = 0; y < cubeInfo.size; y++) {
  43560. var u = minUV;
  43561. for (var x = 0; x < cubeInfo.size; x++) {
  43562. // World direction (not normalised)
  43563. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43564. worldDirection.normalize();
  43565. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43566. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43567. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43568. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43569. // Handle Integer types.
  43570. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43571. r /= 255;
  43572. g /= 255;
  43573. b /= 255;
  43574. }
  43575. // Handle Gamma space textures.
  43576. if (cubeInfo.gammaSpace) {
  43577. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43578. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43579. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43580. }
  43581. var color = new BABYLON.Color3(r, g, b);
  43582. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43583. totalSolidAngle += deltaSolidAngle;
  43584. u += du;
  43585. }
  43586. v += dv;
  43587. }
  43588. }
  43589. // Solid angle for entire sphere is 4*pi
  43590. var sphereSolidAngle = 4.0 * Math.PI;
  43591. // Adjust the solid angle to allow for how many faces we processed.
  43592. var facesProcessed = 6.0;
  43593. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43594. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43595. // This is needed because the numerical integration over the cube uses a
  43596. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43597. // and also to compensate for accumulative error due to float precision in the summation.
  43598. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43599. sphericalHarmonics.scale(correctionFactor);
  43600. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43601. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43602. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43603. };
  43604. CubeMapToSphericalPolynomialTools.FileFaces = [
  43605. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43606. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43607. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43608. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43609. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43610. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43611. ];
  43612. return CubeMapToSphericalPolynomialTools;
  43613. }());
  43614. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43615. })(BABYLON || (BABYLON = {}));
  43616. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43617. var BABYLON;
  43618. (function (BABYLON) {
  43619. /**
  43620. * Manages the defines for the PBR Material.
  43621. * @hiddenChildren
  43622. */
  43623. var PBRMaterialDefines = /** @class */ (function (_super) {
  43624. __extends(PBRMaterialDefines, _super);
  43625. /**
  43626. * Initializes the PBR Material defines.
  43627. */
  43628. function PBRMaterialDefines() {
  43629. var _this = _super.call(this) || this;
  43630. _this.PBR = true;
  43631. _this.MAINUV1 = false;
  43632. _this.MAINUV2 = false;
  43633. _this.UV1 = false;
  43634. _this.UV2 = false;
  43635. _this.ALBEDO = false;
  43636. _this.ALBEDODIRECTUV = 0;
  43637. _this.VERTEXCOLOR = false;
  43638. _this.AMBIENT = false;
  43639. _this.AMBIENTDIRECTUV = 0;
  43640. _this.AMBIENTINGRAYSCALE = false;
  43641. _this.OPACITY = false;
  43642. _this.VERTEXALPHA = false;
  43643. _this.OPACITYDIRECTUV = 0;
  43644. _this.OPACITYRGB = false;
  43645. _this.ALPHATEST = false;
  43646. _this.DEPTHPREPASS = false;
  43647. _this.ALPHABLEND = false;
  43648. _this.ALPHAFROMALBEDO = false;
  43649. _this.ALPHATESTVALUE = "0.5";
  43650. _this.SPECULAROVERALPHA = false;
  43651. _this.RADIANCEOVERALPHA = false;
  43652. _this.ALPHAFRESNEL = false;
  43653. _this.LINEARALPHAFRESNEL = false;
  43654. _this.PREMULTIPLYALPHA = false;
  43655. _this.EMISSIVE = false;
  43656. _this.EMISSIVEDIRECTUV = 0;
  43657. _this.REFLECTIVITY = false;
  43658. _this.REFLECTIVITYDIRECTUV = 0;
  43659. _this.SPECULARTERM = false;
  43660. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43661. _this.MICROSURFACEAUTOMATIC = false;
  43662. _this.LODBASEDMICROSFURACE = false;
  43663. _this.MICROSURFACEMAP = false;
  43664. _this.MICROSURFACEMAPDIRECTUV = 0;
  43665. _this.METALLICWORKFLOW = false;
  43666. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43667. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43668. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43669. _this.AOSTOREINMETALMAPRED = false;
  43670. _this.ENVIRONMENTBRDF = false;
  43671. _this.NORMAL = false;
  43672. _this.TANGENT = false;
  43673. _this.BUMP = false;
  43674. _this.BUMPDIRECTUV = 0;
  43675. _this.OBJECTSPACE_NORMALMAP = false;
  43676. _this.PARALLAX = false;
  43677. _this.PARALLAXOCCLUSION = false;
  43678. _this.NORMALXYSCALE = true;
  43679. _this.LIGHTMAP = false;
  43680. _this.LIGHTMAPDIRECTUV = 0;
  43681. _this.USELIGHTMAPASSHADOWMAP = false;
  43682. _this.GAMMALIGHTMAP = false;
  43683. _this.REFLECTION = false;
  43684. _this.REFLECTIONMAP_3D = false;
  43685. _this.REFLECTIONMAP_SPHERICAL = false;
  43686. _this.REFLECTIONMAP_PLANAR = false;
  43687. _this.REFLECTIONMAP_CUBIC = false;
  43688. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43689. _this.REFLECTIONMAP_PROJECTION = false;
  43690. _this.REFLECTIONMAP_SKYBOX = false;
  43691. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43692. _this.REFLECTIONMAP_EXPLICIT = false;
  43693. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43694. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43695. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43696. _this.INVERTCUBICMAP = false;
  43697. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43698. _this.USESPHERICALINVERTEX = false;
  43699. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43700. _this.LODINREFLECTIONALPHA = false;
  43701. _this.GAMMAREFLECTION = false;
  43702. _this.RGBDREFLECTION = false;
  43703. _this.RADIANCEOCCLUSION = false;
  43704. _this.HORIZONOCCLUSION = false;
  43705. _this.REFRACTION = false;
  43706. _this.REFRACTIONMAP_3D = false;
  43707. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43708. _this.LODINREFRACTIONALPHA = false;
  43709. _this.GAMMAREFRACTION = false;
  43710. _this.RGBDREFRACTION = false;
  43711. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43712. _this.INSTANCES = false;
  43713. _this.NUM_BONE_INFLUENCERS = 0;
  43714. _this.BonesPerMesh = 0;
  43715. _this.NONUNIFORMSCALING = false;
  43716. _this.MORPHTARGETS = false;
  43717. _this.MORPHTARGETS_NORMAL = false;
  43718. _this.MORPHTARGETS_TANGENT = false;
  43719. _this.NUM_MORPH_INFLUENCERS = 0;
  43720. _this.IMAGEPROCESSING = false;
  43721. _this.VIGNETTE = false;
  43722. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43723. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43724. _this.TONEMAPPING = false;
  43725. _this.TONEMAPPING_ACES = false;
  43726. _this.CONTRAST = false;
  43727. _this.COLORCURVES = false;
  43728. _this.COLORGRADING = false;
  43729. _this.COLORGRADING3D = false;
  43730. _this.SAMPLER3DGREENDEPTH = false;
  43731. _this.SAMPLER3DBGRMAP = false;
  43732. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43733. _this.EXPOSURE = false;
  43734. _this.USEPHYSICALLIGHTFALLOFF = false;
  43735. _this.USEGLTFLIGHTFALLOFF = false;
  43736. _this.TWOSIDEDLIGHTING = false;
  43737. _this.SHADOWFLOAT = false;
  43738. _this.CLIPPLANE = false;
  43739. _this.CLIPPLANE2 = false;
  43740. _this.CLIPPLANE3 = false;
  43741. _this.CLIPPLANE4 = false;
  43742. _this.POINTSIZE = false;
  43743. _this.FOG = false;
  43744. _this.LOGARITHMICDEPTH = false;
  43745. _this.FORCENORMALFORWARD = false;
  43746. _this.SPECULARAA = false;
  43747. _this.UNLIT = false;
  43748. _this.rebuild();
  43749. return _this;
  43750. }
  43751. /**
  43752. * Resets the PBR Material defines.
  43753. */
  43754. PBRMaterialDefines.prototype.reset = function () {
  43755. _super.prototype.reset.call(this);
  43756. this.ALPHATESTVALUE = "0.5";
  43757. this.PBR = true;
  43758. };
  43759. return PBRMaterialDefines;
  43760. }(BABYLON.MaterialDefines));
  43761. /**
  43762. * The Physically based material base class of BJS.
  43763. *
  43764. * This offers the main features of a standard PBR material.
  43765. * For more information, please refer to the documentation :
  43766. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43767. */
  43768. var PBRBaseMaterial = /** @class */ (function (_super) {
  43769. __extends(PBRBaseMaterial, _super);
  43770. /**
  43771. * Instantiates a new PBRMaterial instance.
  43772. *
  43773. * @param name The material name
  43774. * @param scene The scene the material will be use in.
  43775. */
  43776. function PBRBaseMaterial(name, scene) {
  43777. var _this = _super.call(this, name, scene) || this;
  43778. /**
  43779. * Intensity of the direct lights e.g. the four lights available in your scene.
  43780. * This impacts both the direct diffuse and specular highlights.
  43781. */
  43782. _this._directIntensity = 1.0;
  43783. /**
  43784. * Intensity of the emissive part of the material.
  43785. * This helps controlling the emissive effect without modifying the emissive color.
  43786. */
  43787. _this._emissiveIntensity = 1.0;
  43788. /**
  43789. * Intensity of the environment e.g. how much the environment will light the object
  43790. * either through harmonics for rough material or through the refelction for shiny ones.
  43791. */
  43792. _this._environmentIntensity = 1.0;
  43793. /**
  43794. * This is a special control allowing the reduction of the specular highlights coming from the
  43795. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43796. */
  43797. _this._specularIntensity = 1.0;
  43798. /**
  43799. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43800. */
  43801. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43802. /**
  43803. * Debug Control allowing disabling the bump map on this material.
  43804. */
  43805. _this._disableBumpMap = false;
  43806. /**
  43807. * AKA Occlusion Texture Intensity in other nomenclature.
  43808. */
  43809. _this._ambientTextureStrength = 1.0;
  43810. /**
  43811. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43812. * 1 means it completely occludes it
  43813. * 0 mean it has no impact
  43814. */
  43815. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43816. /**
  43817. * The color of a material in ambient lighting.
  43818. */
  43819. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43820. /**
  43821. * AKA Diffuse Color in other nomenclature.
  43822. */
  43823. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43824. /**
  43825. * AKA Specular Color in other nomenclature.
  43826. */
  43827. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43828. /**
  43829. * The color applied when light is reflected from a material.
  43830. */
  43831. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43832. /**
  43833. * The color applied when light is emitted from a material.
  43834. */
  43835. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43836. /**
  43837. * AKA Glossiness in other nomenclature.
  43838. */
  43839. _this._microSurface = 0.9;
  43840. /**
  43841. * source material index of refraction (IOR)' / 'destination material IOR.
  43842. */
  43843. _this._indexOfRefraction = 0.66;
  43844. /**
  43845. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43846. */
  43847. _this._invertRefractionY = false;
  43848. /**
  43849. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43850. * Materials half opaque for instance using refraction could benefit from this control.
  43851. */
  43852. _this._linkRefractionWithTransparency = false;
  43853. /**
  43854. * Specifies that the material will use the light map as a show map.
  43855. */
  43856. _this._useLightmapAsShadowmap = false;
  43857. /**
  43858. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43859. * makes the reflect vector face the model (under horizon).
  43860. */
  43861. _this._useHorizonOcclusion = true;
  43862. /**
  43863. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43864. * too much the area relying on ambient texture to define their ambient occlusion.
  43865. */
  43866. _this._useRadianceOcclusion = true;
  43867. /**
  43868. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43869. */
  43870. _this._useAlphaFromAlbedoTexture = false;
  43871. /**
  43872. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43873. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43874. */
  43875. _this._useSpecularOverAlpha = true;
  43876. /**
  43877. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43878. */
  43879. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43880. /**
  43881. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43882. */
  43883. _this._useRoughnessFromMetallicTextureAlpha = true;
  43884. /**
  43885. * Specifies if the metallic texture contains the roughness information in its green channel.
  43886. */
  43887. _this._useRoughnessFromMetallicTextureGreen = false;
  43888. /**
  43889. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43890. */
  43891. _this._useMetallnessFromMetallicTextureBlue = false;
  43892. /**
  43893. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43894. */
  43895. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43896. /**
  43897. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43898. */
  43899. _this._useAmbientInGrayScale = false;
  43900. /**
  43901. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43902. * The material will try to infer what glossiness each pixel should be.
  43903. */
  43904. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43905. /**
  43906. * Defines the falloff type used in this material.
  43907. * It by default is Physical.
  43908. */
  43909. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43910. /**
  43911. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43912. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43913. */
  43914. _this._useRadianceOverAlpha = true;
  43915. /**
  43916. * Allows using an object space normal map (instead of tangent space).
  43917. */
  43918. _this._useObjectSpaceNormalMap = false;
  43919. /**
  43920. * Allows using the bump map in parallax mode.
  43921. */
  43922. _this._useParallax = false;
  43923. /**
  43924. * Allows using the bump map in parallax occlusion mode.
  43925. */
  43926. _this._useParallaxOcclusion = false;
  43927. /**
  43928. * Controls the scale bias of the parallax mode.
  43929. */
  43930. _this._parallaxScaleBias = 0.05;
  43931. /**
  43932. * If sets to true, disables all the lights affecting the material.
  43933. */
  43934. _this._disableLighting = false;
  43935. /**
  43936. * Number of Simultaneous lights allowed on the material.
  43937. */
  43938. _this._maxSimultaneousLights = 4;
  43939. /**
  43940. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43941. */
  43942. _this._invertNormalMapX = false;
  43943. /**
  43944. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43945. */
  43946. _this._invertNormalMapY = false;
  43947. /**
  43948. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43949. */
  43950. _this._twoSidedLighting = false;
  43951. /**
  43952. * Defines the alpha limits in alpha test mode.
  43953. */
  43954. _this._alphaCutOff = 0.4;
  43955. /**
  43956. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43957. */
  43958. _this._forceAlphaTest = false;
  43959. /**
  43960. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43961. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43962. */
  43963. _this._useAlphaFresnel = false;
  43964. /**
  43965. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43966. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43967. */
  43968. _this._useLinearAlphaFresnel = false;
  43969. /**
  43970. * The transparency mode of the material.
  43971. */
  43972. _this._transparencyMode = null;
  43973. /**
  43974. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43975. * from cos thetav and roughness:
  43976. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43977. */
  43978. _this._environmentBRDFTexture = null;
  43979. /**
  43980. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43981. */
  43982. _this._forceIrradianceInFragment = false;
  43983. /**
  43984. * Force normal to face away from face.
  43985. */
  43986. _this._forceNormalForward = false;
  43987. /**
  43988. * Enables specular anti aliasing in the PBR shader.
  43989. * It will both interacts on the Geometry for analytical and IBL lighting.
  43990. * It also prefilter the roughness map based on the bump values.
  43991. */
  43992. _this._enableSpecularAntiAliasing = false;
  43993. /**
  43994. * Stores the available render targets.
  43995. */
  43996. _this._renderTargets = new BABYLON.SmartArray(16);
  43997. /**
  43998. * Sets the global ambient color for the material used in lighting calculations.
  43999. */
  44000. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44001. /**
  44002. * If set to true, no lighting calculations will be applied.
  44003. */
  44004. _this._unlit = false;
  44005. // Setup the default processing configuration to the scene.
  44006. _this._attachImageProcessingConfiguration(null);
  44007. _this.getRenderTargetTextures = function () {
  44008. _this._renderTargets.reset();
  44009. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44010. _this._renderTargets.push(_this._reflectionTexture);
  44011. }
  44012. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44013. _this._renderTargets.push(_this._refractionTexture);
  44014. }
  44015. return _this._renderTargets;
  44016. };
  44017. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44018. return _this;
  44019. }
  44020. /**
  44021. * Attaches a new image processing configuration to the PBR Material.
  44022. * @param configuration
  44023. */
  44024. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44025. var _this = this;
  44026. if (configuration === this._imageProcessingConfiguration) {
  44027. return;
  44028. }
  44029. // Detaches observer.
  44030. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44031. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44032. }
  44033. // Pick the scene configuration if needed.
  44034. if (!configuration) {
  44035. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44036. }
  44037. else {
  44038. this._imageProcessingConfiguration = configuration;
  44039. }
  44040. // Attaches observer.
  44041. if (this._imageProcessingConfiguration) {
  44042. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44043. _this._markAllSubMeshesAsImageProcessingDirty();
  44044. });
  44045. }
  44046. };
  44047. /**
  44048. * Gets the name of the material class.
  44049. */
  44050. PBRBaseMaterial.prototype.getClassName = function () {
  44051. return "PBRBaseMaterial";
  44052. };
  44053. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44054. /**
  44055. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44056. */
  44057. get: function () {
  44058. return this._useLogarithmicDepth;
  44059. },
  44060. /**
  44061. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44062. */
  44063. set: function (value) {
  44064. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44065. },
  44066. enumerable: true,
  44067. configurable: true
  44068. });
  44069. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44070. /**
  44071. * Gets the current transparency mode.
  44072. */
  44073. get: function () {
  44074. return this._transparencyMode;
  44075. },
  44076. /**
  44077. * Sets the transparency mode of the material.
  44078. *
  44079. * | Value | Type | Description |
  44080. * | ----- | ----------------------------------- | ----------- |
  44081. * | 0 | OPAQUE | |
  44082. * | 1 | ALPHATEST | |
  44083. * | 2 | ALPHABLEND | |
  44084. * | 3 | ALPHATESTANDBLEND | |
  44085. *
  44086. */
  44087. set: function (value) {
  44088. if (this._transparencyMode === value) {
  44089. return;
  44090. }
  44091. this._transparencyMode = value;
  44092. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44093. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44094. },
  44095. enumerable: true,
  44096. configurable: true
  44097. });
  44098. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44099. /**
  44100. * Returns true if alpha blending should be disabled.
  44101. */
  44102. get: function () {
  44103. return (this._linkRefractionWithTransparency ||
  44104. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44105. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44106. },
  44107. enumerable: true,
  44108. configurable: true
  44109. });
  44110. /**
  44111. * Specifies whether or not this material should be rendered in alpha blend mode.
  44112. */
  44113. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44114. if (this._disableAlphaBlending) {
  44115. return false;
  44116. }
  44117. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44118. };
  44119. /**
  44120. * Specifies if the mesh will require alpha blending.
  44121. * @param mesh - BJS mesh.
  44122. */
  44123. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44124. if (this._disableAlphaBlending) {
  44125. return false;
  44126. }
  44127. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44128. };
  44129. /**
  44130. * Specifies whether or not this material should be rendered in alpha test mode.
  44131. */
  44132. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44133. if (this._forceAlphaTest) {
  44134. return true;
  44135. }
  44136. if (this._linkRefractionWithTransparency) {
  44137. return false;
  44138. }
  44139. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44140. };
  44141. /**
  44142. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44143. */
  44144. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44145. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44146. };
  44147. /**
  44148. * Gets the texture used for the alpha test.
  44149. */
  44150. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44151. return this._albedoTexture;
  44152. };
  44153. /**
  44154. * Specifies that the submesh is ready to be used.
  44155. * @param mesh - BJS mesh.
  44156. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44157. * @param useInstances - Specifies that instances should be used.
  44158. * @returns - boolean indicating that the submesh is ready or not.
  44159. */
  44160. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44161. if (subMesh.effect && this.isFrozen) {
  44162. if (this._wasPreviouslyReady) {
  44163. return true;
  44164. }
  44165. }
  44166. if (!subMesh._materialDefines) {
  44167. subMesh._materialDefines = new PBRMaterialDefines();
  44168. }
  44169. var defines = subMesh._materialDefines;
  44170. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44171. if (defines._renderId === this.getScene().getRenderId()) {
  44172. return true;
  44173. }
  44174. }
  44175. var scene = this.getScene();
  44176. var engine = scene.getEngine();
  44177. if (defines._areTexturesDirty) {
  44178. if (scene.texturesEnabled) {
  44179. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44180. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44181. return false;
  44182. }
  44183. }
  44184. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44185. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44186. return false;
  44187. }
  44188. }
  44189. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44190. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44191. return false;
  44192. }
  44193. }
  44194. var reflectionTexture = this._getReflectionTexture();
  44195. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44196. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44197. return false;
  44198. }
  44199. }
  44200. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44201. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44202. return false;
  44203. }
  44204. }
  44205. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44206. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44207. return false;
  44208. }
  44209. }
  44210. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44211. if (this._metallicTexture) {
  44212. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44213. return false;
  44214. }
  44215. }
  44216. else if (this._reflectivityTexture) {
  44217. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44218. return false;
  44219. }
  44220. }
  44221. if (this._microSurfaceTexture) {
  44222. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44223. return false;
  44224. }
  44225. }
  44226. }
  44227. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44228. // Bump texture cannot be not blocking.
  44229. if (!this._bumpTexture.isReady()) {
  44230. return false;
  44231. }
  44232. }
  44233. var refractionTexture = this._getRefractionTexture();
  44234. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44235. if (!refractionTexture.isReadyOrNotBlocking()) {
  44236. return false;
  44237. }
  44238. }
  44239. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44240. // This is blocking.
  44241. if (!this._environmentBRDFTexture.isReady()) {
  44242. return false;
  44243. }
  44244. }
  44245. }
  44246. }
  44247. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44248. if (!this._imageProcessingConfiguration.isReady()) {
  44249. return false;
  44250. }
  44251. }
  44252. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44253. mesh.createNormals(true);
  44254. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44255. }
  44256. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44257. if (effect) {
  44258. scene.resetCachedMaterial();
  44259. subMesh.setEffect(effect, defines);
  44260. this.buildUniformLayout();
  44261. }
  44262. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44263. return false;
  44264. }
  44265. defines._renderId = scene.getRenderId();
  44266. this._wasPreviouslyReady = true;
  44267. return true;
  44268. };
  44269. /**
  44270. * Specifies if the material uses metallic roughness workflow.
  44271. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44272. */
  44273. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44274. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44275. return true;
  44276. }
  44277. return false;
  44278. };
  44279. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44280. if (onCompiled === void 0) { onCompiled = null; }
  44281. if (onError === void 0) { onError = null; }
  44282. if (useInstances === void 0) { useInstances = null; }
  44283. if (useClipPlane === void 0) { useClipPlane = null; }
  44284. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44285. if (!defines.isDirty) {
  44286. return null;
  44287. }
  44288. defines.markAsProcessed();
  44289. var scene = this.getScene();
  44290. var engine = scene.getEngine();
  44291. // Fallbacks
  44292. var fallbacks = new BABYLON.EffectFallbacks();
  44293. var fallbackRank = 0;
  44294. if (defines.USESPHERICALINVERTEX) {
  44295. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44296. }
  44297. if (defines.FOG) {
  44298. fallbacks.addFallback(fallbackRank, "FOG");
  44299. }
  44300. if (defines.SPECULARAA) {
  44301. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44302. }
  44303. if (defines.POINTSIZE) {
  44304. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44305. }
  44306. if (defines.LOGARITHMICDEPTH) {
  44307. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44308. }
  44309. if (defines.PARALLAX) {
  44310. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44311. }
  44312. if (defines.PARALLAXOCCLUSION) {
  44313. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44314. }
  44315. if (defines.ENVIRONMENTBRDF) {
  44316. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44317. }
  44318. if (defines.TANGENT) {
  44319. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44320. }
  44321. if (defines.BUMP) {
  44322. fallbacks.addFallback(fallbackRank++, "BUMP");
  44323. }
  44324. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44325. if (defines.SPECULARTERM) {
  44326. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44327. }
  44328. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44329. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44330. }
  44331. if (defines.LIGHTMAP) {
  44332. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44333. }
  44334. if (defines.NORMAL) {
  44335. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44336. }
  44337. if (defines.AMBIENT) {
  44338. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44339. }
  44340. if (defines.EMISSIVE) {
  44341. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44342. }
  44343. if (defines.VERTEXCOLOR) {
  44344. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44345. }
  44346. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44347. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44348. }
  44349. if (defines.MORPHTARGETS) {
  44350. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44351. }
  44352. //Attributes
  44353. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44354. if (defines.NORMAL) {
  44355. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44356. }
  44357. if (defines.TANGENT) {
  44358. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44359. }
  44360. if (defines.UV1) {
  44361. attribs.push(BABYLON.VertexBuffer.UVKind);
  44362. }
  44363. if (defines.UV2) {
  44364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44365. }
  44366. if (defines.VERTEXCOLOR) {
  44367. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44368. }
  44369. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44370. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44371. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44372. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44373. "vFogInfos", "vFogColor", "pointSize",
  44374. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44375. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44376. "mBones",
  44377. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44378. "vLightingIntensity",
  44379. "logarithmicDepthConstant",
  44380. "vSphericalX", "vSphericalY", "vSphericalZ",
  44381. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44382. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44383. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44384. "vTangentSpaceParams"
  44385. ];
  44386. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44387. "bumpSampler", "lightmapSampler", "opacitySampler",
  44388. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44389. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44390. "microSurfaceSampler", "environmentBrdfSampler"];
  44391. var uniformBuffers = ["Material", "Scene"];
  44392. if (BABYLON.ImageProcessingConfiguration) {
  44393. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44394. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44395. }
  44396. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44397. uniformsNames: uniforms,
  44398. uniformBuffersNames: uniformBuffers,
  44399. samplers: samplers,
  44400. defines: defines,
  44401. maxSimultaneousLights: this._maxSimultaneousLights
  44402. });
  44403. var join = defines.toString();
  44404. return engine.createEffect("pbr", {
  44405. attributes: attribs,
  44406. uniformsNames: uniforms,
  44407. uniformBuffersNames: uniformBuffers,
  44408. samplers: samplers,
  44409. defines: join,
  44410. fallbacks: fallbacks,
  44411. onCompiled: onCompiled,
  44412. onError: onError,
  44413. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44414. }, engine);
  44415. };
  44416. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44417. if (useInstances === void 0) { useInstances = null; }
  44418. if (useClipPlane === void 0) { useClipPlane = null; }
  44419. var scene = this.getScene();
  44420. var engine = scene.getEngine();
  44421. // Lights
  44422. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44423. defines._needNormals = true;
  44424. // Textures
  44425. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44426. if (defines._areTexturesDirty) {
  44427. defines._needUVs = false;
  44428. if (scene.texturesEnabled) {
  44429. if (scene.getEngine().getCaps().textureLOD) {
  44430. defines.LODBASEDMICROSFURACE = true;
  44431. }
  44432. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44433. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44434. }
  44435. else {
  44436. defines.ALBEDO = false;
  44437. }
  44438. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44439. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44440. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44441. }
  44442. else {
  44443. defines.AMBIENT = false;
  44444. }
  44445. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44446. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44447. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44448. }
  44449. else {
  44450. defines.OPACITY = false;
  44451. }
  44452. var reflectionTexture = this._getReflectionTexture();
  44453. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44454. defines.REFLECTION = true;
  44455. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44456. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44457. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44458. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44459. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44460. defines.INVERTCUBICMAP = true;
  44461. }
  44462. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44463. switch (reflectionTexture.coordinatesMode) {
  44464. case BABYLON.Texture.EXPLICIT_MODE:
  44465. defines.REFLECTIONMAP_EXPLICIT = true;
  44466. break;
  44467. case BABYLON.Texture.PLANAR_MODE:
  44468. defines.REFLECTIONMAP_PLANAR = true;
  44469. break;
  44470. case BABYLON.Texture.PROJECTION_MODE:
  44471. defines.REFLECTIONMAP_PROJECTION = true;
  44472. break;
  44473. case BABYLON.Texture.SKYBOX_MODE:
  44474. defines.REFLECTIONMAP_SKYBOX = true;
  44475. break;
  44476. case BABYLON.Texture.SPHERICAL_MODE:
  44477. defines.REFLECTIONMAP_SPHERICAL = true;
  44478. break;
  44479. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44480. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44481. break;
  44482. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44483. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44484. break;
  44485. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44486. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44487. break;
  44488. case BABYLON.Texture.CUBIC_MODE:
  44489. case BABYLON.Texture.INVCUBIC_MODE:
  44490. default:
  44491. defines.REFLECTIONMAP_CUBIC = true;
  44492. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44493. break;
  44494. }
  44495. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44496. if (reflectionTexture.sphericalPolynomial) {
  44497. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44498. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44499. defines.USESPHERICALINVERTEX = false;
  44500. }
  44501. else {
  44502. defines.USESPHERICALINVERTEX = true;
  44503. }
  44504. }
  44505. }
  44506. else {
  44507. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44508. }
  44509. }
  44510. else {
  44511. defines.REFLECTION = false;
  44512. defines.REFLECTIONMAP_3D = false;
  44513. defines.REFLECTIONMAP_SPHERICAL = false;
  44514. defines.REFLECTIONMAP_PLANAR = false;
  44515. defines.REFLECTIONMAP_CUBIC = false;
  44516. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44517. defines.REFLECTIONMAP_PROJECTION = false;
  44518. defines.REFLECTIONMAP_SKYBOX = false;
  44519. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44520. defines.REFLECTIONMAP_EXPLICIT = false;
  44521. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44522. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44523. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44524. defines.INVERTCUBICMAP = false;
  44525. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44526. defines.USESPHERICALINVERTEX = false;
  44527. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44528. defines.LODINREFLECTIONALPHA = false;
  44529. defines.GAMMAREFLECTION = false;
  44530. defines.RGBDREFLECTION = false;
  44531. }
  44532. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44533. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44534. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44535. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44536. }
  44537. else {
  44538. defines.LIGHTMAP = false;
  44539. }
  44540. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44541. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44542. }
  44543. else {
  44544. defines.EMISSIVE = false;
  44545. }
  44546. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44547. if (this._metallicTexture) {
  44548. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44549. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44550. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44551. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44552. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44553. }
  44554. else if (this._reflectivityTexture) {
  44555. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44556. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44557. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44558. }
  44559. else {
  44560. defines.REFLECTIVITY = false;
  44561. }
  44562. if (this._microSurfaceTexture) {
  44563. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44564. }
  44565. else {
  44566. defines.MICROSURFACEMAP = false;
  44567. }
  44568. }
  44569. else {
  44570. defines.REFLECTIVITY = false;
  44571. defines.MICROSURFACEMAP = false;
  44572. }
  44573. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44574. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44575. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44576. defines.PARALLAX = true;
  44577. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44578. }
  44579. else {
  44580. defines.PARALLAX = false;
  44581. }
  44582. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44583. }
  44584. else {
  44585. defines.BUMP = false;
  44586. }
  44587. var refractionTexture = this._getRefractionTexture();
  44588. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44589. defines.REFRACTION = true;
  44590. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44591. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44592. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44593. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44594. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44595. if (this._linkRefractionWithTransparency) {
  44596. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44597. }
  44598. }
  44599. else {
  44600. defines.REFRACTION = false;
  44601. }
  44602. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44603. defines.ENVIRONMENTBRDF = true;
  44604. }
  44605. else {
  44606. defines.ENVIRONMENTBRDF = false;
  44607. }
  44608. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44609. defines.ALPHAFROMALBEDO = true;
  44610. }
  44611. else {
  44612. defines.ALPHAFROMALBEDO = false;
  44613. }
  44614. }
  44615. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44616. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44617. defines.USEPHYSICALLIGHTFALLOFF = false;
  44618. defines.USEGLTFLIGHTFALLOFF = false;
  44619. }
  44620. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44621. defines.USEPHYSICALLIGHTFALLOFF = false;
  44622. defines.USEGLTFLIGHTFALLOFF = true;
  44623. }
  44624. else {
  44625. defines.USEPHYSICALLIGHTFALLOFF = true;
  44626. defines.USEGLTFLIGHTFALLOFF = false;
  44627. }
  44628. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44629. if (!this.backFaceCulling && this._twoSidedLighting) {
  44630. defines.TWOSIDEDLIGHTING = true;
  44631. }
  44632. else {
  44633. defines.TWOSIDEDLIGHTING = false;
  44634. }
  44635. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44636. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44637. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44638. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44639. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44640. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44641. }
  44642. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44643. this._imageProcessingConfiguration.prepareDefines(defines);
  44644. }
  44645. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44646. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44647. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44648. // Misc.
  44649. if (defines._areMiscDirty) {
  44650. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44651. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44652. }
  44653. // Values that need to be evaluated on every frame
  44654. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44655. // Attribs
  44656. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44657. };
  44658. /**
  44659. * Force shader compilation
  44660. */
  44661. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44662. var _this = this;
  44663. var localOptions = __assign({ clipPlane: false }, options);
  44664. var defines = new PBRMaterialDefines();
  44665. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44666. if (effect.isReady()) {
  44667. if (onCompiled) {
  44668. onCompiled(this);
  44669. }
  44670. }
  44671. else {
  44672. effect.onCompileObservable.add(function () {
  44673. if (onCompiled) {
  44674. onCompiled(_this);
  44675. }
  44676. });
  44677. }
  44678. };
  44679. /**
  44680. * Initializes the uniform buffer layout for the shader.
  44681. */
  44682. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44683. // Order is important !
  44684. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44685. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44686. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44687. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44688. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44689. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44690. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44691. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44692. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44693. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44694. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44695. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44696. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44697. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44698. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44699. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44700. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44701. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44702. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44703. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44704. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44705. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44706. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44707. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44708. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44709. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44710. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44711. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44712. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44713. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44714. this._uniformBuffer.addUniform("pointSize", 1);
  44715. this._uniformBuffer.create();
  44716. };
  44717. /**
  44718. * Unbinds the textures.
  44719. */
  44720. PBRBaseMaterial.prototype.unbind = function () {
  44721. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44722. this._uniformBuffer.setTexture("reflectionSampler", null);
  44723. }
  44724. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44725. this._uniformBuffer.setTexture("refractionSampler", null);
  44726. }
  44727. _super.prototype.unbind.call(this);
  44728. };
  44729. /**
  44730. * Binds the submesh data.
  44731. * @param world - The world matrix.
  44732. * @param mesh - The BJS mesh.
  44733. * @param subMesh - A submesh of the BJS mesh.
  44734. */
  44735. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44736. var scene = this.getScene();
  44737. var defines = subMesh._materialDefines;
  44738. if (!defines) {
  44739. return;
  44740. }
  44741. var effect = subMesh.effect;
  44742. if (!effect) {
  44743. return;
  44744. }
  44745. this._activeEffect = effect;
  44746. // Matrices
  44747. this.bindOnlyWorldMatrix(world);
  44748. // Normal Matrix
  44749. if (defines.OBJECTSPACE_NORMALMAP) {
  44750. world.toNormalMatrix(this._normalMatrix);
  44751. this.bindOnlyNormalMatrix(this._normalMatrix);
  44752. }
  44753. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44754. // Bones
  44755. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44756. var reflectionTexture = null;
  44757. if (mustRebind) {
  44758. this._uniformBuffer.bindToEffect(effect, "Material");
  44759. this.bindViewProjection(effect);
  44760. reflectionTexture = this._getReflectionTexture();
  44761. var refractionTexture = this._getRefractionTexture();
  44762. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44763. // Texture uniforms
  44764. if (scene.texturesEnabled) {
  44765. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44766. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44767. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44768. }
  44769. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44770. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44771. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44772. }
  44773. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44774. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44775. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44776. }
  44777. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44778. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44779. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44780. if (reflectionTexture.boundingBoxSize) {
  44781. var cubeTexture = reflectionTexture;
  44782. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44783. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44784. }
  44785. var polynomials = reflectionTexture.sphericalPolynomial;
  44786. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44787. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44788. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44789. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44790. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44791. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44792. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44793. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44794. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44795. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44796. }
  44797. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44798. }
  44799. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44800. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44801. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44802. }
  44803. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44804. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44805. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44806. }
  44807. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44808. if (this._metallicTexture) {
  44809. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44810. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44811. }
  44812. else if (this._reflectivityTexture) {
  44813. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44814. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44815. }
  44816. if (this._microSurfaceTexture) {
  44817. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44818. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44819. }
  44820. }
  44821. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44822. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44823. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44824. if (scene._mirroredCameraPosition) {
  44825. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44826. }
  44827. else {
  44828. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44829. }
  44830. }
  44831. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44832. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44833. var depth = 1.0;
  44834. if (!refractionTexture.isCube) {
  44835. if (refractionTexture.depth) {
  44836. depth = refractionTexture.depth;
  44837. }
  44838. }
  44839. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44840. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44841. }
  44842. }
  44843. // Point size
  44844. if (this.pointsCloud) {
  44845. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44846. }
  44847. // Colors
  44848. if (defines.METALLICWORKFLOW) {
  44849. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44850. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44851. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44852. }
  44853. else {
  44854. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44855. }
  44856. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44857. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44858. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44859. // Misc
  44860. this._lightingInfos.x = this._directIntensity;
  44861. this._lightingInfos.y = this._emissiveIntensity;
  44862. this._lightingInfos.z = this._environmentIntensity;
  44863. this._lightingInfos.w = this._specularIntensity;
  44864. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44865. }
  44866. // Textures
  44867. if (scene.texturesEnabled) {
  44868. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44869. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44870. }
  44871. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44872. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44873. }
  44874. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44875. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44876. }
  44877. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44878. if (defines.LODBASEDMICROSFURACE) {
  44879. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44880. }
  44881. else {
  44882. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44883. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44884. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44885. }
  44886. }
  44887. if (defines.ENVIRONMENTBRDF) {
  44888. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44889. }
  44890. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44891. if (defines.LODBASEDMICROSFURACE) {
  44892. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44893. }
  44894. else {
  44895. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44896. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44897. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44898. }
  44899. }
  44900. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44901. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44902. }
  44903. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44904. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44905. }
  44906. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44907. if (this._metallicTexture) {
  44908. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44909. }
  44910. else if (this._reflectivityTexture) {
  44911. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44912. }
  44913. if (this._microSurfaceTexture) {
  44914. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44915. }
  44916. }
  44917. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44918. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44919. }
  44920. }
  44921. // Clip plane
  44922. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44923. // Colors
  44924. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44925. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44926. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44927. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44928. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44929. }
  44930. if (mustRebind || !this.isFrozen) {
  44931. // Lights
  44932. if (scene.lightsEnabled && !this._disableLighting) {
  44933. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44934. }
  44935. // View
  44936. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44937. this.bindView(effect);
  44938. }
  44939. // Fog
  44940. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44941. // Morph targets
  44942. if (defines.NUM_MORPH_INFLUENCERS) {
  44943. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44944. }
  44945. // image processing
  44946. this._imageProcessingConfiguration.bind(this._activeEffect);
  44947. // Log. depth
  44948. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44949. }
  44950. this._uniformBuffer.update();
  44951. this._afterBind(mesh, this._activeEffect);
  44952. };
  44953. /**
  44954. * Returns the animatable textures.
  44955. * @returns - Array of animatable textures.
  44956. */
  44957. PBRBaseMaterial.prototype.getAnimatables = function () {
  44958. var results = [];
  44959. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44960. results.push(this._albedoTexture);
  44961. }
  44962. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44963. results.push(this._ambientTexture);
  44964. }
  44965. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44966. results.push(this._opacityTexture);
  44967. }
  44968. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44969. results.push(this._reflectionTexture);
  44970. }
  44971. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44972. results.push(this._emissiveTexture);
  44973. }
  44974. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44975. results.push(this._metallicTexture);
  44976. }
  44977. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44978. results.push(this._reflectivityTexture);
  44979. }
  44980. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44981. results.push(this._bumpTexture);
  44982. }
  44983. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44984. results.push(this._lightmapTexture);
  44985. }
  44986. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44987. results.push(this._refractionTexture);
  44988. }
  44989. return results;
  44990. };
  44991. /**
  44992. * Returns the texture used for reflections.
  44993. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44994. */
  44995. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44996. if (this._reflectionTexture) {
  44997. return this._reflectionTexture;
  44998. }
  44999. return this.getScene().environmentTexture;
  45000. };
  45001. /**
  45002. * Returns the texture used for refraction or null if none is used.
  45003. * @returns - Refection texture if present. If no refraction texture and refraction
  45004. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45005. */
  45006. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45007. if (this._refractionTexture) {
  45008. return this._refractionTexture;
  45009. }
  45010. if (this._linkRefractionWithTransparency) {
  45011. return this.getScene().environmentTexture;
  45012. }
  45013. return null;
  45014. };
  45015. /**
  45016. * Disposes the resources of the material.
  45017. * @param forceDisposeEffect - Forces the disposal of effects.
  45018. * @param forceDisposeTextures - Forces the disposal of all textures.
  45019. */
  45020. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45021. if (forceDisposeTextures) {
  45022. if (this._albedoTexture) {
  45023. this._albedoTexture.dispose();
  45024. }
  45025. if (this._ambientTexture) {
  45026. this._ambientTexture.dispose();
  45027. }
  45028. if (this._opacityTexture) {
  45029. this._opacityTexture.dispose();
  45030. }
  45031. if (this._reflectionTexture) {
  45032. this._reflectionTexture.dispose();
  45033. }
  45034. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45035. this._environmentBRDFTexture.dispose();
  45036. }
  45037. if (this._emissiveTexture) {
  45038. this._emissiveTexture.dispose();
  45039. }
  45040. if (this._metallicTexture) {
  45041. this._metallicTexture.dispose();
  45042. }
  45043. if (this._reflectivityTexture) {
  45044. this._reflectivityTexture.dispose();
  45045. }
  45046. if (this._bumpTexture) {
  45047. this._bumpTexture.dispose();
  45048. }
  45049. if (this._lightmapTexture) {
  45050. this._lightmapTexture.dispose();
  45051. }
  45052. if (this._refractionTexture) {
  45053. this._refractionTexture.dispose();
  45054. }
  45055. }
  45056. this._renderTargets.dispose();
  45057. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45058. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45059. }
  45060. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45061. };
  45062. /**
  45063. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45064. */
  45065. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45066. /**
  45067. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45068. * to enhance interoperability with other engines.
  45069. */
  45070. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45071. /**
  45072. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45073. * to enhance interoperability with other materials.
  45074. */
  45075. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45076. /**
  45077. * Stores the reflectivity values based on metallic roughness workflow.
  45078. */
  45079. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45080. __decorate([
  45081. BABYLON.serializeAsImageProcessingConfiguration()
  45082. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45083. __decorate([
  45084. BABYLON.serialize()
  45085. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45086. __decorate([
  45087. BABYLON.serialize()
  45088. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45089. return PBRBaseMaterial;
  45090. }(BABYLON.PushMaterial));
  45091. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45092. })(BABYLON || (BABYLON = {}));
  45093. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45094. var BABYLON;
  45095. (function (BABYLON) {
  45096. /**
  45097. * The Physically based simple base material of BJS.
  45098. *
  45099. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45100. * It is used as the base class for both the specGloss and metalRough conventions.
  45101. */
  45102. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45103. __extends(PBRBaseSimpleMaterial, _super);
  45104. /**
  45105. * Instantiates a new PBRMaterial instance.
  45106. *
  45107. * @param name The material name
  45108. * @param scene The scene the material will be use in.
  45109. */
  45110. function PBRBaseSimpleMaterial(name, scene) {
  45111. var _this = _super.call(this, name, scene) || this;
  45112. /**
  45113. * Number of Simultaneous lights allowed on the material.
  45114. */
  45115. _this.maxSimultaneousLights = 4;
  45116. /**
  45117. * If sets to true, disables all the lights affecting the material.
  45118. */
  45119. _this.disableLighting = false;
  45120. /**
  45121. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45122. */
  45123. _this.invertNormalMapX = false;
  45124. /**
  45125. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45126. */
  45127. _this.invertNormalMapY = false;
  45128. /**
  45129. * Emissivie color used to self-illuminate the model.
  45130. */
  45131. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45132. /**
  45133. * Occlusion Channel Strenght.
  45134. */
  45135. _this.occlusionStrength = 1.0;
  45136. _this.useLightmapAsShadowmap = false;
  45137. _this._useAlphaFromAlbedoTexture = true;
  45138. _this._useAmbientInGrayScale = true;
  45139. return _this;
  45140. }
  45141. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45142. /**
  45143. * Gets the current double sided mode.
  45144. */
  45145. get: function () {
  45146. return this._twoSidedLighting;
  45147. },
  45148. /**
  45149. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45150. */
  45151. set: function (value) {
  45152. if (this._twoSidedLighting === value) {
  45153. return;
  45154. }
  45155. this._twoSidedLighting = value;
  45156. this.backFaceCulling = !value;
  45157. this._markAllSubMeshesAsTexturesDirty();
  45158. },
  45159. enumerable: true,
  45160. configurable: true
  45161. });
  45162. /**
  45163. * Return the active textures of the material.
  45164. */
  45165. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45166. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45167. if (this.environmentTexture) {
  45168. activeTextures.push(this.environmentTexture);
  45169. }
  45170. if (this.normalTexture) {
  45171. activeTextures.push(this.normalTexture);
  45172. }
  45173. if (this.emissiveTexture) {
  45174. activeTextures.push(this.emissiveTexture);
  45175. }
  45176. if (this.occlusionTexture) {
  45177. activeTextures.push(this.occlusionTexture);
  45178. }
  45179. if (this.lightmapTexture) {
  45180. activeTextures.push(this.lightmapTexture);
  45181. }
  45182. return activeTextures;
  45183. };
  45184. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45185. if (_super.prototype.hasTexture.call(this, texture)) {
  45186. return true;
  45187. }
  45188. if (this.lightmapTexture === texture) {
  45189. return true;
  45190. }
  45191. return false;
  45192. };
  45193. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45194. return "PBRBaseSimpleMaterial";
  45195. };
  45196. __decorate([
  45197. BABYLON.serialize(),
  45198. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45199. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45200. __decorate([
  45201. BABYLON.serialize(),
  45202. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45203. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45204. __decorate([
  45205. BABYLON.serializeAsTexture(),
  45206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45207. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45208. __decorate([
  45209. BABYLON.serialize(),
  45210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45211. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45212. __decorate([
  45213. BABYLON.serialize(),
  45214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45215. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45216. __decorate([
  45217. BABYLON.serializeAsTexture(),
  45218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45219. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45220. __decorate([
  45221. BABYLON.serializeAsColor3("emissive"),
  45222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45223. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45224. __decorate([
  45225. BABYLON.serializeAsTexture(),
  45226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45227. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45228. __decorate([
  45229. BABYLON.serialize(),
  45230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45231. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45232. __decorate([
  45233. BABYLON.serializeAsTexture(),
  45234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45235. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45236. __decorate([
  45237. BABYLON.serialize(),
  45238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45239. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45240. __decorate([
  45241. BABYLON.serialize()
  45242. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45243. __decorate([
  45244. BABYLON.serializeAsTexture(),
  45245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45246. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45247. __decorate([
  45248. BABYLON.serialize(),
  45249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45250. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45251. return PBRBaseSimpleMaterial;
  45252. }(BABYLON.PBRBaseMaterial));
  45253. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45254. })(BABYLON || (BABYLON = {}));
  45255. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45256. var BABYLON;
  45257. (function (BABYLON) {
  45258. /**
  45259. * The Physically based material of BJS.
  45260. *
  45261. * This offers the main features of a standard PBR material.
  45262. * For more information, please refer to the documentation :
  45263. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45264. */
  45265. var PBRMaterial = /** @class */ (function (_super) {
  45266. __extends(PBRMaterial, _super);
  45267. /**
  45268. * Instantiates a new PBRMaterial instance.
  45269. *
  45270. * @param name The material name
  45271. * @param scene The scene the material will be use in.
  45272. */
  45273. function PBRMaterial(name, scene) {
  45274. var _this = _super.call(this, name, scene) || this;
  45275. /**
  45276. * Intensity of the direct lights e.g. the four lights available in your scene.
  45277. * This impacts both the direct diffuse and specular highlights.
  45278. */
  45279. _this.directIntensity = 1.0;
  45280. /**
  45281. * Intensity of the emissive part of the material.
  45282. * This helps controlling the emissive effect without modifying the emissive color.
  45283. */
  45284. _this.emissiveIntensity = 1.0;
  45285. /**
  45286. * Intensity of the environment e.g. how much the environment will light the object
  45287. * either through harmonics for rough material or through the refelction for shiny ones.
  45288. */
  45289. _this.environmentIntensity = 1.0;
  45290. /**
  45291. * This is a special control allowing the reduction of the specular highlights coming from the
  45292. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45293. */
  45294. _this.specularIntensity = 1.0;
  45295. /**
  45296. * Debug Control allowing disabling the bump map on this material.
  45297. */
  45298. _this.disableBumpMap = false;
  45299. /**
  45300. * AKA Occlusion Texture Intensity in other nomenclature.
  45301. */
  45302. _this.ambientTextureStrength = 1.0;
  45303. /**
  45304. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45305. * 1 means it completely occludes it
  45306. * 0 mean it has no impact
  45307. */
  45308. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45309. /**
  45310. * The color of a material in ambient lighting.
  45311. */
  45312. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45313. /**
  45314. * AKA Diffuse Color in other nomenclature.
  45315. */
  45316. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45317. /**
  45318. * AKA Specular Color in other nomenclature.
  45319. */
  45320. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45321. /**
  45322. * The color reflected from the material.
  45323. */
  45324. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45325. /**
  45326. * The color emitted from the material.
  45327. */
  45328. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45329. /**
  45330. * AKA Glossiness in other nomenclature.
  45331. */
  45332. _this.microSurface = 1.0;
  45333. /**
  45334. * source material index of refraction (IOR)' / 'destination material IOR.
  45335. */
  45336. _this.indexOfRefraction = 0.66;
  45337. /**
  45338. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45339. */
  45340. _this.invertRefractionY = false;
  45341. /**
  45342. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45343. * Materials half opaque for instance using refraction could benefit from this control.
  45344. */
  45345. _this.linkRefractionWithTransparency = false;
  45346. _this.useLightmapAsShadowmap = false;
  45347. /**
  45348. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45349. */
  45350. _this.useAlphaFromAlbedoTexture = false;
  45351. /**
  45352. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45353. */
  45354. _this.forceAlphaTest = false;
  45355. /**
  45356. * Defines the alpha limits in alpha test mode.
  45357. */
  45358. _this.alphaCutOff = 0.4;
  45359. /**
  45360. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45361. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45362. */
  45363. _this.useSpecularOverAlpha = true;
  45364. /**
  45365. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45366. */
  45367. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45368. /**
  45369. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45370. */
  45371. _this.useRoughnessFromMetallicTextureAlpha = true;
  45372. /**
  45373. * Specifies if the metallic texture contains the roughness information in its green channel.
  45374. */
  45375. _this.useRoughnessFromMetallicTextureGreen = false;
  45376. /**
  45377. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45378. */
  45379. _this.useMetallnessFromMetallicTextureBlue = false;
  45380. /**
  45381. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45382. */
  45383. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45384. /**
  45385. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45386. */
  45387. _this.useAmbientInGrayScale = false;
  45388. /**
  45389. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45390. * The material will try to infer what glossiness each pixel should be.
  45391. */
  45392. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45393. /**
  45394. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45395. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45396. */
  45397. _this.useRadianceOverAlpha = true;
  45398. /**
  45399. * Allows using an object space normal map (instead of tangent space).
  45400. */
  45401. _this.useObjectSpaceNormalMap = false;
  45402. /**
  45403. * Allows using the bump map in parallax mode.
  45404. */
  45405. _this.useParallax = false;
  45406. /**
  45407. * Allows using the bump map in parallax occlusion mode.
  45408. */
  45409. _this.useParallaxOcclusion = false;
  45410. /**
  45411. * Controls the scale bias of the parallax mode.
  45412. */
  45413. _this.parallaxScaleBias = 0.05;
  45414. /**
  45415. * If sets to true, disables all the lights affecting the material.
  45416. */
  45417. _this.disableLighting = false;
  45418. /**
  45419. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45420. */
  45421. _this.forceIrradianceInFragment = false;
  45422. /**
  45423. * Number of Simultaneous lights allowed on the material.
  45424. */
  45425. _this.maxSimultaneousLights = 4;
  45426. /**
  45427. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45428. */
  45429. _this.invertNormalMapX = false;
  45430. /**
  45431. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45432. */
  45433. _this.invertNormalMapY = false;
  45434. /**
  45435. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45436. */
  45437. _this.twoSidedLighting = false;
  45438. /**
  45439. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45440. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45441. */
  45442. _this.useAlphaFresnel = false;
  45443. /**
  45444. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45445. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45446. */
  45447. _this.useLinearAlphaFresnel = false;
  45448. /**
  45449. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45450. * And/Or occlude the blended part.
  45451. */
  45452. _this.environmentBRDFTexture = null;
  45453. /**
  45454. * Force normal to face away from face.
  45455. */
  45456. _this.forceNormalForward = false;
  45457. /**
  45458. * Enables specular anti aliasing in the PBR shader.
  45459. * It will both interacts on the Geometry for analytical and IBL lighting.
  45460. * It also prefilter the roughness map based on the bump values.
  45461. */
  45462. _this.enableSpecularAntiAliasing = false;
  45463. /**
  45464. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45465. * makes the reflect vector face the model (under horizon).
  45466. */
  45467. _this.useHorizonOcclusion = true;
  45468. /**
  45469. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45470. * too much the area relying on ambient texture to define their ambient occlusion.
  45471. */
  45472. _this.useRadianceOcclusion = true;
  45473. /**
  45474. * If set to true, no lighting calculations will be applied.
  45475. */
  45476. _this.unlit = false;
  45477. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45478. return _this;
  45479. }
  45480. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45481. /**
  45482. * BJS is using an harcoded light falloff based on a manually sets up range.
  45483. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45484. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45485. */
  45486. get: function () {
  45487. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45488. },
  45489. /**
  45490. * BJS is using an harcoded light falloff based on a manually sets up range.
  45491. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45492. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45493. */
  45494. set: function (value) {
  45495. if (value !== this.usePhysicalLightFalloff) {
  45496. // Ensure the effect will be rebuilt.
  45497. this._markAllSubMeshesAsTexturesDirty();
  45498. if (value) {
  45499. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45500. }
  45501. else {
  45502. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45503. }
  45504. }
  45505. },
  45506. enumerable: true,
  45507. configurable: true
  45508. });
  45509. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45510. /**
  45511. * In order to support the falloff compatibility with gltf, a special mode has been added
  45512. * to reproduce the gltf light falloff.
  45513. */
  45514. get: function () {
  45515. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45516. },
  45517. /**
  45518. * In order to support the falloff compatibility with gltf, a special mode has been added
  45519. * to reproduce the gltf light falloff.
  45520. */
  45521. set: function (value) {
  45522. if (value !== this.useGLTFLightFalloff) {
  45523. // Ensure the effect will be rebuilt.
  45524. this._markAllSubMeshesAsTexturesDirty();
  45525. if (value) {
  45526. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45527. }
  45528. else {
  45529. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45530. }
  45531. }
  45532. },
  45533. enumerable: true,
  45534. configurable: true
  45535. });
  45536. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45537. /**
  45538. * Gets the image processing configuration used either in this material.
  45539. */
  45540. get: function () {
  45541. return this._imageProcessingConfiguration;
  45542. },
  45543. /**
  45544. * Sets the Default image processing configuration used either in the this material.
  45545. *
  45546. * If sets to null, the scene one is in use.
  45547. */
  45548. set: function (value) {
  45549. this._attachImageProcessingConfiguration(value);
  45550. // Ensure the effect will be rebuilt.
  45551. this._markAllSubMeshesAsTexturesDirty();
  45552. },
  45553. enumerable: true,
  45554. configurable: true
  45555. });
  45556. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45557. /**
  45558. * Gets wether the color curves effect is enabled.
  45559. */
  45560. get: function () {
  45561. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45562. },
  45563. /**
  45564. * Sets wether the color curves effect is enabled.
  45565. */
  45566. set: function (value) {
  45567. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45568. },
  45569. enumerable: true,
  45570. configurable: true
  45571. });
  45572. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45573. /**
  45574. * Gets wether the color grading effect is enabled.
  45575. */
  45576. get: function () {
  45577. return this.imageProcessingConfiguration.colorGradingEnabled;
  45578. },
  45579. /**
  45580. * Gets wether the color grading effect is enabled.
  45581. */
  45582. set: function (value) {
  45583. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45584. },
  45585. enumerable: true,
  45586. configurable: true
  45587. });
  45588. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45589. /**
  45590. * Gets wether tonemapping is enabled or not.
  45591. */
  45592. get: function () {
  45593. return this._imageProcessingConfiguration.toneMappingEnabled;
  45594. },
  45595. /**
  45596. * Sets wether tonemapping is enabled or not
  45597. */
  45598. set: function (value) {
  45599. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45600. },
  45601. enumerable: true,
  45602. configurable: true
  45603. });
  45604. ;
  45605. ;
  45606. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45607. /**
  45608. * The camera exposure used on this material.
  45609. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45610. * This corresponds to a photographic exposure.
  45611. */
  45612. get: function () {
  45613. return this._imageProcessingConfiguration.exposure;
  45614. },
  45615. /**
  45616. * The camera exposure used on this material.
  45617. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45618. * This corresponds to a photographic exposure.
  45619. */
  45620. set: function (value) {
  45621. this._imageProcessingConfiguration.exposure = value;
  45622. },
  45623. enumerable: true,
  45624. configurable: true
  45625. });
  45626. ;
  45627. ;
  45628. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45629. /**
  45630. * Gets The camera contrast used on this material.
  45631. */
  45632. get: function () {
  45633. return this._imageProcessingConfiguration.contrast;
  45634. },
  45635. /**
  45636. * Sets The camera contrast used on this material.
  45637. */
  45638. set: function (value) {
  45639. this._imageProcessingConfiguration.contrast = value;
  45640. },
  45641. enumerable: true,
  45642. configurable: true
  45643. });
  45644. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45645. /**
  45646. * Gets the Color Grading 2D Lookup Texture.
  45647. */
  45648. get: function () {
  45649. return this._imageProcessingConfiguration.colorGradingTexture;
  45650. },
  45651. /**
  45652. * Sets the Color Grading 2D Lookup Texture.
  45653. */
  45654. set: function (value) {
  45655. this._imageProcessingConfiguration.colorGradingTexture = value;
  45656. },
  45657. enumerable: true,
  45658. configurable: true
  45659. });
  45660. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45661. /**
  45662. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45663. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45664. * 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;
  45665. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45666. */
  45667. get: function () {
  45668. return this._imageProcessingConfiguration.colorCurves;
  45669. },
  45670. /**
  45671. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45672. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45673. * 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;
  45674. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45675. */
  45676. set: function (value) {
  45677. this._imageProcessingConfiguration.colorCurves = value;
  45678. },
  45679. enumerable: true,
  45680. configurable: true
  45681. });
  45682. /**
  45683. * Returns the name of this material class.
  45684. */
  45685. PBRMaterial.prototype.getClassName = function () {
  45686. return "PBRMaterial";
  45687. };
  45688. /**
  45689. * Returns an array of the actively used textures.
  45690. * @returns - Array of BaseTextures
  45691. */
  45692. PBRMaterial.prototype.getActiveTextures = function () {
  45693. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45694. if (this._albedoTexture) {
  45695. activeTextures.push(this._albedoTexture);
  45696. }
  45697. if (this._ambientTexture) {
  45698. activeTextures.push(this._ambientTexture);
  45699. }
  45700. if (this._opacityTexture) {
  45701. activeTextures.push(this._opacityTexture);
  45702. }
  45703. if (this._reflectionTexture) {
  45704. activeTextures.push(this._reflectionTexture);
  45705. }
  45706. if (this._emissiveTexture) {
  45707. activeTextures.push(this._emissiveTexture);
  45708. }
  45709. if (this._reflectivityTexture) {
  45710. activeTextures.push(this._reflectivityTexture);
  45711. }
  45712. if (this._metallicTexture) {
  45713. activeTextures.push(this._metallicTexture);
  45714. }
  45715. if (this._microSurfaceTexture) {
  45716. activeTextures.push(this._microSurfaceTexture);
  45717. }
  45718. if (this._bumpTexture) {
  45719. activeTextures.push(this._bumpTexture);
  45720. }
  45721. if (this._lightmapTexture) {
  45722. activeTextures.push(this._lightmapTexture);
  45723. }
  45724. if (this._refractionTexture) {
  45725. activeTextures.push(this._refractionTexture);
  45726. }
  45727. return activeTextures;
  45728. };
  45729. /**
  45730. * Checks to see if a texture is used in the material.
  45731. * @param texture - Base texture to use.
  45732. * @returns - Boolean specifying if a texture is used in the material.
  45733. */
  45734. PBRMaterial.prototype.hasTexture = function (texture) {
  45735. if (_super.prototype.hasTexture.call(this, texture)) {
  45736. return true;
  45737. }
  45738. if (this._albedoTexture === texture) {
  45739. return true;
  45740. }
  45741. if (this._ambientTexture === texture) {
  45742. return true;
  45743. }
  45744. if (this._opacityTexture === texture) {
  45745. return true;
  45746. }
  45747. if (this._reflectionTexture === texture) {
  45748. return true;
  45749. }
  45750. if (this._reflectivityTexture === texture) {
  45751. return true;
  45752. }
  45753. if (this._metallicTexture === texture) {
  45754. return true;
  45755. }
  45756. if (this._microSurfaceTexture === texture) {
  45757. return true;
  45758. }
  45759. if (this._bumpTexture === texture) {
  45760. return true;
  45761. }
  45762. if (this._lightmapTexture === texture) {
  45763. return true;
  45764. }
  45765. if (this._refractionTexture === texture) {
  45766. return true;
  45767. }
  45768. return false;
  45769. };
  45770. /**
  45771. * Makes a duplicate of the current material.
  45772. * @param name - name to use for the new material.
  45773. */
  45774. PBRMaterial.prototype.clone = function (name) {
  45775. var _this = this;
  45776. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45777. clone.id = name;
  45778. clone.name = name;
  45779. return clone;
  45780. };
  45781. /**
  45782. * Serializes this PBR Material.
  45783. * @returns - An object with the serialized material.
  45784. */
  45785. PBRMaterial.prototype.serialize = function () {
  45786. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45787. serializationObject.customType = "BABYLON.PBRMaterial";
  45788. return serializationObject;
  45789. };
  45790. // Statics
  45791. /**
  45792. * Parses a PBR Material from a serialized object.
  45793. * @param source - Serialized object.
  45794. * @param scene - BJS scene instance.
  45795. * @param rootUrl - url for the scene object
  45796. * @returns - PBRMaterial
  45797. */
  45798. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45799. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45800. };
  45801. /**
  45802. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45803. */
  45804. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45805. /**
  45806. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45807. */
  45808. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45809. /**
  45810. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45811. */
  45812. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45813. /**
  45814. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45815. * They are also discarded below the alpha cutoff threshold to improve performances.
  45816. */
  45817. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45818. /**
  45819. * Defines the default value of how much AO map is occluding the analytical lights
  45820. * (point spot...).
  45821. */
  45822. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45823. __decorate([
  45824. BABYLON.serialize(),
  45825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45826. ], PBRMaterial.prototype, "directIntensity", void 0);
  45827. __decorate([
  45828. BABYLON.serialize(),
  45829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45830. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45831. __decorate([
  45832. BABYLON.serialize(),
  45833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45834. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45835. __decorate([
  45836. BABYLON.serialize(),
  45837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45838. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45839. __decorate([
  45840. BABYLON.serialize(),
  45841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45842. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45843. __decorate([
  45844. BABYLON.serializeAsTexture(),
  45845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45846. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45847. __decorate([
  45848. BABYLON.serializeAsTexture(),
  45849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45850. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45851. __decorate([
  45852. BABYLON.serialize(),
  45853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45854. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45855. __decorate([
  45856. BABYLON.serialize(),
  45857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45858. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45859. __decorate([
  45860. BABYLON.serializeAsTexture(),
  45861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45862. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45863. __decorate([
  45864. BABYLON.serializeAsTexture(),
  45865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45866. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45867. __decorate([
  45868. BABYLON.serializeAsTexture(),
  45869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45870. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45871. __decorate([
  45872. BABYLON.serializeAsTexture(),
  45873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45874. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45875. __decorate([
  45876. BABYLON.serializeAsTexture(),
  45877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45878. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45879. __decorate([
  45880. BABYLON.serialize(),
  45881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45882. ], PBRMaterial.prototype, "metallic", void 0);
  45883. __decorate([
  45884. BABYLON.serialize(),
  45885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45886. ], PBRMaterial.prototype, "roughness", void 0);
  45887. __decorate([
  45888. BABYLON.serializeAsTexture(),
  45889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45890. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45891. __decorate([
  45892. BABYLON.serializeAsTexture(),
  45893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45894. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45895. __decorate([
  45896. BABYLON.serializeAsTexture(),
  45897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45898. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45899. __decorate([
  45900. BABYLON.serializeAsTexture(),
  45901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45902. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45903. __decorate([
  45904. BABYLON.serializeAsColor3("ambient"),
  45905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45906. ], PBRMaterial.prototype, "ambientColor", void 0);
  45907. __decorate([
  45908. BABYLON.serializeAsColor3("albedo"),
  45909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45910. ], PBRMaterial.prototype, "albedoColor", void 0);
  45911. __decorate([
  45912. BABYLON.serializeAsColor3("reflectivity"),
  45913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45914. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45915. __decorate([
  45916. BABYLON.serializeAsColor3("reflection"),
  45917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45918. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45919. __decorate([
  45920. BABYLON.serializeAsColor3("emissive"),
  45921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45922. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45923. __decorate([
  45924. BABYLON.serialize(),
  45925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45926. ], PBRMaterial.prototype, "microSurface", void 0);
  45927. __decorate([
  45928. BABYLON.serialize(),
  45929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45930. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45931. __decorate([
  45932. BABYLON.serialize(),
  45933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45934. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45935. __decorate([
  45936. BABYLON.serialize(),
  45937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45938. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45939. __decorate([
  45940. BABYLON.serialize(),
  45941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45942. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45943. __decorate([
  45944. BABYLON.serialize(),
  45945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45946. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45947. __decorate([
  45948. BABYLON.serialize(),
  45949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45950. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45951. __decorate([
  45952. BABYLON.serialize(),
  45953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45954. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45955. __decorate([
  45956. BABYLON.serialize(),
  45957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45958. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45959. __decorate([
  45960. BABYLON.serialize(),
  45961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45962. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45963. __decorate([
  45964. BABYLON.serialize(),
  45965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45966. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45967. __decorate([
  45968. BABYLON.serialize(),
  45969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45970. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45971. __decorate([
  45972. BABYLON.serialize(),
  45973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45974. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45975. __decorate([
  45976. BABYLON.serialize(),
  45977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45978. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45979. __decorate([
  45980. BABYLON.serialize(),
  45981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45982. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45983. __decorate([
  45984. BABYLON.serialize(),
  45985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45986. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45987. __decorate([
  45988. BABYLON.serialize()
  45989. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45990. __decorate([
  45991. BABYLON.serialize()
  45992. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45993. __decorate([
  45994. BABYLON.serialize(),
  45995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45996. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45997. __decorate([
  45998. BABYLON.serialize(),
  45999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46000. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46001. __decorate([
  46002. BABYLON.serialize(),
  46003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46004. ], PBRMaterial.prototype, "useParallax", void 0);
  46005. __decorate([
  46006. BABYLON.serialize(),
  46007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46008. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46009. __decorate([
  46010. BABYLON.serialize(),
  46011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46012. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46013. __decorate([
  46014. BABYLON.serialize(),
  46015. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46016. ], PBRMaterial.prototype, "disableLighting", void 0);
  46017. __decorate([
  46018. BABYLON.serialize(),
  46019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46020. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46021. __decorate([
  46022. BABYLON.serialize(),
  46023. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46024. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46025. __decorate([
  46026. BABYLON.serialize(),
  46027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46028. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46029. __decorate([
  46030. BABYLON.serialize(),
  46031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46032. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46033. __decorate([
  46034. BABYLON.serialize(),
  46035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46036. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46037. __decorate([
  46038. BABYLON.serialize(),
  46039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46040. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46041. __decorate([
  46042. BABYLON.serialize(),
  46043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46044. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46045. __decorate([
  46046. BABYLON.serializeAsTexture(),
  46047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46048. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46049. __decorate([
  46050. BABYLON.serialize(),
  46051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46052. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46053. __decorate([
  46054. BABYLON.serialize(),
  46055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46056. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46057. __decorate([
  46058. BABYLON.serialize(),
  46059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46060. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46061. __decorate([
  46062. BABYLON.serialize(),
  46063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46064. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46065. __decorate([
  46066. BABYLON.serialize(),
  46067. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46068. ], PBRMaterial.prototype, "unlit", void 0);
  46069. return PBRMaterial;
  46070. }(BABYLON.PBRBaseMaterial));
  46071. BABYLON.PBRMaterial = PBRMaterial;
  46072. })(BABYLON || (BABYLON = {}));
  46073. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46074. var BABYLON;
  46075. (function (BABYLON) {
  46076. /**
  46077. * The PBR material of BJS following the metal roughness convention.
  46078. *
  46079. * This fits to the PBR convention in the GLTF definition:
  46080. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46081. */
  46082. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46083. __extends(PBRMetallicRoughnessMaterial, _super);
  46084. /**
  46085. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46086. *
  46087. * @param name The material name
  46088. * @param scene The scene the material will be use in.
  46089. */
  46090. function PBRMetallicRoughnessMaterial(name, scene) {
  46091. var _this = _super.call(this, name, scene) || this;
  46092. _this._useRoughnessFromMetallicTextureAlpha = false;
  46093. _this._useRoughnessFromMetallicTextureGreen = true;
  46094. _this._useMetallnessFromMetallicTextureBlue = true;
  46095. _this.metallic = 1.0;
  46096. _this.roughness = 1.0;
  46097. return _this;
  46098. }
  46099. /**
  46100. * Return the currrent class name of the material.
  46101. */
  46102. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46103. return "PBRMetallicRoughnessMaterial";
  46104. };
  46105. /**
  46106. * Return the active textures of the material.
  46107. */
  46108. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46109. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46110. if (this.baseTexture) {
  46111. activeTextures.push(this.baseTexture);
  46112. }
  46113. if (this.metallicRoughnessTexture) {
  46114. activeTextures.push(this.metallicRoughnessTexture);
  46115. }
  46116. return activeTextures;
  46117. };
  46118. /**
  46119. * Checks to see if a texture is used in the material.
  46120. * @param texture - Base texture to use.
  46121. * @returns - Boolean specifying if a texture is used in the material.
  46122. */
  46123. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46124. if (_super.prototype.hasTexture.call(this, texture)) {
  46125. return true;
  46126. }
  46127. if (this.baseTexture === texture) {
  46128. return true;
  46129. }
  46130. if (this.metallicRoughnessTexture === texture) {
  46131. return true;
  46132. }
  46133. return false;
  46134. };
  46135. /**
  46136. * Makes a duplicate of the current material.
  46137. * @param name - name to use for the new material.
  46138. */
  46139. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46140. var _this = this;
  46141. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46142. clone.id = name;
  46143. clone.name = name;
  46144. return clone;
  46145. };
  46146. /**
  46147. * Serialize the material to a parsable JSON object.
  46148. */
  46149. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46150. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46151. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46152. return serializationObject;
  46153. };
  46154. /**
  46155. * Parses a JSON object correponding to the serialize function.
  46156. */
  46157. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46158. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46159. };
  46160. __decorate([
  46161. BABYLON.serializeAsColor3(),
  46162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46163. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46164. __decorate([
  46165. BABYLON.serializeAsTexture(),
  46166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46167. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46168. __decorate([
  46169. BABYLON.serialize(),
  46170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46171. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46172. __decorate([
  46173. BABYLON.serialize(),
  46174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46175. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46176. __decorate([
  46177. BABYLON.serializeAsTexture(),
  46178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46179. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46180. return PBRMetallicRoughnessMaterial;
  46181. }(BABYLON.PBRBaseSimpleMaterial));
  46182. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46183. })(BABYLON || (BABYLON = {}));
  46184. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46185. var BABYLON;
  46186. (function (BABYLON) {
  46187. /**
  46188. * The PBR material of BJS following the specular glossiness convention.
  46189. *
  46190. * This fits to the PBR convention in the GLTF definition:
  46191. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46192. */
  46193. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46194. __extends(PBRSpecularGlossinessMaterial, _super);
  46195. /**
  46196. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46197. *
  46198. * @param name The material name
  46199. * @param scene The scene the material will be use in.
  46200. */
  46201. function PBRSpecularGlossinessMaterial(name, scene) {
  46202. var _this = _super.call(this, name, scene) || this;
  46203. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46204. return _this;
  46205. }
  46206. /**
  46207. * Return the currrent class name of the material.
  46208. */
  46209. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46210. return "PBRSpecularGlossinessMaterial";
  46211. };
  46212. /**
  46213. * Return the active textures of the material.
  46214. */
  46215. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46216. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46217. if (this.diffuseTexture) {
  46218. activeTextures.push(this.diffuseTexture);
  46219. }
  46220. if (this.specularGlossinessTexture) {
  46221. activeTextures.push(this.specularGlossinessTexture);
  46222. }
  46223. return activeTextures;
  46224. };
  46225. /**
  46226. * Checks to see if a texture is used in the material.
  46227. * @param texture - Base texture to use.
  46228. * @returns - Boolean specifying if a texture is used in the material.
  46229. */
  46230. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46231. if (_super.prototype.hasTexture.call(this, texture)) {
  46232. return true;
  46233. }
  46234. if (this.diffuseTexture === texture) {
  46235. return true;
  46236. }
  46237. if (this.specularGlossinessTexture === texture) {
  46238. return true;
  46239. }
  46240. return false;
  46241. };
  46242. /**
  46243. * Makes a duplicate of the current material.
  46244. * @param name - name to use for the new material.
  46245. */
  46246. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46247. var _this = this;
  46248. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46249. clone.id = name;
  46250. clone.name = name;
  46251. return clone;
  46252. };
  46253. /**
  46254. * Serialize the material to a parsable JSON object.
  46255. */
  46256. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46257. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46258. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46259. return serializationObject;
  46260. };
  46261. /**
  46262. * Parses a JSON object correponding to the serialize function.
  46263. */
  46264. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46265. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46266. };
  46267. __decorate([
  46268. BABYLON.serializeAsColor3("diffuse"),
  46269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46270. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46271. __decorate([
  46272. BABYLON.serializeAsTexture(),
  46273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46274. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46275. __decorate([
  46276. BABYLON.serializeAsColor3("specular"),
  46277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46278. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46279. __decorate([
  46280. BABYLON.serialize(),
  46281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46282. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46283. __decorate([
  46284. BABYLON.serializeAsTexture(),
  46285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46286. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46287. return PBRSpecularGlossinessMaterial;
  46288. }(BABYLON.PBRBaseSimpleMaterial));
  46289. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46290. })(BABYLON || (BABYLON = {}));
  46291. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46292. var BABYLON;
  46293. (function (BABYLON) {
  46294. BABYLON.CameraInputTypes = {};
  46295. var CameraInputsManager = /** @class */ (function () {
  46296. function CameraInputsManager(camera) {
  46297. this.attached = {};
  46298. this.camera = camera;
  46299. this.checkInputs = function () { };
  46300. }
  46301. /**
  46302. * Add an input method to a camera
  46303. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46304. * @param input camera input method
  46305. */
  46306. CameraInputsManager.prototype.add = function (input) {
  46307. var type = input.getSimpleName();
  46308. if (this.attached[type]) {
  46309. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46310. return;
  46311. }
  46312. this.attached[type] = input;
  46313. input.camera = this.camera;
  46314. //for checkInputs, we are dynamically creating a function
  46315. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46316. if (input.checkInputs) {
  46317. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46318. }
  46319. if (this.attachedElement) {
  46320. input.attachControl(this.attachedElement);
  46321. }
  46322. };
  46323. /**
  46324. * Remove a specific input method from a camera
  46325. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46326. * @param inputToRemove camera input method
  46327. */
  46328. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46329. for (var cam in this.attached) {
  46330. var input = this.attached[cam];
  46331. if (input === inputToRemove) {
  46332. input.detachControl(this.attachedElement);
  46333. input.camera = null;
  46334. delete this.attached[cam];
  46335. this.rebuildInputCheck();
  46336. }
  46337. }
  46338. };
  46339. CameraInputsManager.prototype.removeByType = function (inputType) {
  46340. for (var cam in this.attached) {
  46341. var input = this.attached[cam];
  46342. if (input.getClassName() === inputType) {
  46343. input.detachControl(this.attachedElement);
  46344. input.camera = null;
  46345. delete this.attached[cam];
  46346. this.rebuildInputCheck();
  46347. }
  46348. }
  46349. };
  46350. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46351. var current = this.checkInputs;
  46352. return function () {
  46353. current();
  46354. fn();
  46355. };
  46356. };
  46357. CameraInputsManager.prototype.attachInput = function (input) {
  46358. if (this.attachedElement) {
  46359. input.attachControl(this.attachedElement, this.noPreventDefault);
  46360. }
  46361. };
  46362. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46363. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46364. if (this.attachedElement) {
  46365. return;
  46366. }
  46367. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46368. this.attachedElement = element;
  46369. this.noPreventDefault = noPreventDefault;
  46370. for (var cam in this.attached) {
  46371. this.attached[cam].attachControl(element, noPreventDefault);
  46372. }
  46373. };
  46374. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46375. if (disconnect === void 0) { disconnect = false; }
  46376. if (this.attachedElement !== element) {
  46377. return;
  46378. }
  46379. for (var cam in this.attached) {
  46380. this.attached[cam].detachControl(element);
  46381. if (disconnect) {
  46382. this.attached[cam].camera = null;
  46383. }
  46384. }
  46385. this.attachedElement = null;
  46386. };
  46387. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46388. this.checkInputs = function () { };
  46389. for (var cam in this.attached) {
  46390. var input = this.attached[cam];
  46391. if (input.checkInputs) {
  46392. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46393. }
  46394. }
  46395. };
  46396. /**
  46397. * Remove all attached input methods from a camera
  46398. */
  46399. CameraInputsManager.prototype.clear = function () {
  46400. if (this.attachedElement) {
  46401. this.detachElement(this.attachedElement, true);
  46402. }
  46403. this.attached = {};
  46404. this.attachedElement = null;
  46405. this.checkInputs = function () { };
  46406. };
  46407. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46408. var inputs = {};
  46409. for (var cam in this.attached) {
  46410. var input = this.attached[cam];
  46411. var res = BABYLON.SerializationHelper.Serialize(input);
  46412. inputs[input.getClassName()] = res;
  46413. }
  46414. serializedCamera.inputsmgr = inputs;
  46415. };
  46416. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46417. var parsedInputs = parsedCamera.inputsmgr;
  46418. if (parsedInputs) {
  46419. this.clear();
  46420. for (var n in parsedInputs) {
  46421. var construct = BABYLON.CameraInputTypes[n];
  46422. if (construct) {
  46423. var parsedinput = parsedInputs[n];
  46424. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46425. this.add(input);
  46426. }
  46427. }
  46428. }
  46429. else {
  46430. //2016-03-08 this part is for managing backward compatibility
  46431. for (var n in this.attached) {
  46432. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46433. if (construct) {
  46434. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46435. this.remove(this.attached[n]);
  46436. this.add(input);
  46437. }
  46438. }
  46439. }
  46440. };
  46441. return CameraInputsManager;
  46442. }());
  46443. BABYLON.CameraInputsManager = CameraInputsManager;
  46444. })(BABYLON || (BABYLON = {}));
  46445. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46446. var BABYLON;
  46447. (function (BABYLON) {
  46448. var TargetCamera = /** @class */ (function (_super) {
  46449. __extends(TargetCamera, _super);
  46450. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46451. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46452. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46453. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46454. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46455. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46456. _this.speed = 2.0;
  46457. _this.noRotationConstraint = false;
  46458. _this.lockedTarget = null;
  46459. /** @hidden */
  46460. _this._currentTarget = BABYLON.Vector3.Zero();
  46461. /** @hidden */
  46462. _this._viewMatrix = BABYLON.Matrix.Zero();
  46463. /** @hidden */
  46464. _this._camMatrix = BABYLON.Matrix.Zero();
  46465. /** @hidden */
  46466. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46467. /** @hidden */
  46468. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46469. /** @hidden */
  46470. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46471. /** @hidden */
  46472. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46473. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46474. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46475. _this._defaultUp = BABYLON.Vector3.Up();
  46476. _this._cachedRotationZ = 0;
  46477. return _this;
  46478. }
  46479. TargetCamera.prototype.getFrontPosition = function (distance) {
  46480. this.getWorldMatrix();
  46481. var direction = this.getTarget().subtract(this.position);
  46482. direction.normalize();
  46483. direction.scaleInPlace(distance);
  46484. return this.globalPosition.add(direction);
  46485. };
  46486. /** @hidden */
  46487. TargetCamera.prototype._getLockedTargetPosition = function () {
  46488. if (!this.lockedTarget) {
  46489. return null;
  46490. }
  46491. if (this.lockedTarget.absolutePosition) {
  46492. this.lockedTarget.computeWorldMatrix();
  46493. }
  46494. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46495. };
  46496. TargetCamera.prototype.storeState = function () {
  46497. this._storedPosition = this.position.clone();
  46498. this._storedRotation = this.rotation.clone();
  46499. if (this.rotationQuaternion) {
  46500. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46501. }
  46502. return _super.prototype.storeState.call(this);
  46503. };
  46504. /**
  46505. * Restored camera state. You must call storeState() first
  46506. * @returns whether it was successful or not
  46507. * @hidden
  46508. */
  46509. TargetCamera.prototype._restoreStateValues = function () {
  46510. if (!_super.prototype._restoreStateValues.call(this)) {
  46511. return false;
  46512. }
  46513. this.position = this._storedPosition.clone();
  46514. this.rotation = this._storedRotation.clone();
  46515. if (this.rotationQuaternion) {
  46516. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46517. }
  46518. this.cameraDirection.copyFromFloats(0, 0, 0);
  46519. this.cameraRotation.copyFromFloats(0, 0);
  46520. return true;
  46521. };
  46522. // Cache
  46523. /** @hidden */
  46524. TargetCamera.prototype._initCache = function () {
  46525. _super.prototype._initCache.call(this);
  46526. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46527. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46528. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46529. };
  46530. /** @hidden */
  46531. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46532. if (!ignoreParentClass) {
  46533. _super.prototype._updateCache.call(this);
  46534. }
  46535. var lockedTargetPosition = this._getLockedTargetPosition();
  46536. if (!lockedTargetPosition) {
  46537. this._cache.lockedTarget = null;
  46538. }
  46539. else {
  46540. if (!this._cache.lockedTarget) {
  46541. this._cache.lockedTarget = lockedTargetPosition.clone();
  46542. }
  46543. else {
  46544. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46545. }
  46546. }
  46547. this._cache.rotation.copyFrom(this.rotation);
  46548. if (this.rotationQuaternion)
  46549. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46550. };
  46551. // Synchronized
  46552. /** @hidden */
  46553. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46554. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46555. return false;
  46556. }
  46557. var lockedTargetPosition = this._getLockedTargetPosition();
  46558. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46559. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46560. };
  46561. // Methods
  46562. /** @hidden */
  46563. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46564. var engine = this.getEngine();
  46565. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46566. };
  46567. // Target
  46568. /** @hidden */
  46569. TargetCamera.prototype.setTarget = function (target) {
  46570. this.upVector.normalize();
  46571. if (this.position.z === target.z) {
  46572. this.position.z += BABYLON.Epsilon;
  46573. }
  46574. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46575. this._camMatrix.invert();
  46576. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46577. var vDir = target.subtract(this.position);
  46578. if (vDir.x >= 0.0) {
  46579. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46580. }
  46581. else {
  46582. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46583. }
  46584. this.rotation.z = 0;
  46585. if (isNaN(this.rotation.x)) {
  46586. this.rotation.x = 0;
  46587. }
  46588. if (isNaN(this.rotation.y)) {
  46589. this.rotation.y = 0;
  46590. }
  46591. if (isNaN(this.rotation.z)) {
  46592. this.rotation.z = 0;
  46593. }
  46594. if (this.rotationQuaternion) {
  46595. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46596. }
  46597. };
  46598. /**
  46599. * Return the current target position of the camera. This value is expressed in local space.
  46600. */
  46601. TargetCamera.prototype.getTarget = function () {
  46602. return this._currentTarget;
  46603. };
  46604. /** @hidden */
  46605. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46606. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46607. };
  46608. /** @hidden */
  46609. TargetCamera.prototype._updatePosition = function () {
  46610. if (this.parent) {
  46611. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46612. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46613. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46614. return;
  46615. }
  46616. this.position.addInPlace(this.cameraDirection);
  46617. };
  46618. /** @hidden */
  46619. TargetCamera.prototype._checkInputs = function () {
  46620. var needToMove = this._decideIfNeedsToMove();
  46621. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46622. // Move
  46623. if (needToMove) {
  46624. this._updatePosition();
  46625. }
  46626. // Rotate
  46627. if (needToRotate) {
  46628. this.rotation.x += this.cameraRotation.x;
  46629. this.rotation.y += this.cameraRotation.y;
  46630. //rotate, if quaternion is set and rotation was used
  46631. if (this.rotationQuaternion) {
  46632. var len = this.rotation.lengthSquared();
  46633. if (len) {
  46634. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46635. }
  46636. }
  46637. if (!this.noRotationConstraint) {
  46638. var limit = (Math.PI / 2) * 0.95;
  46639. if (this.rotation.x > limit)
  46640. this.rotation.x = limit;
  46641. if (this.rotation.x < -limit)
  46642. this.rotation.x = -limit;
  46643. }
  46644. }
  46645. // Inertia
  46646. if (needToMove) {
  46647. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46648. this.cameraDirection.x = 0;
  46649. }
  46650. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46651. this.cameraDirection.y = 0;
  46652. }
  46653. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46654. this.cameraDirection.z = 0;
  46655. }
  46656. this.cameraDirection.scaleInPlace(this.inertia);
  46657. }
  46658. if (needToRotate) {
  46659. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46660. this.cameraRotation.x = 0;
  46661. }
  46662. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46663. this.cameraRotation.y = 0;
  46664. }
  46665. this.cameraRotation.scaleInPlace(this.inertia);
  46666. }
  46667. _super.prototype._checkInputs.call(this);
  46668. };
  46669. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46670. if (this.rotationQuaternion) {
  46671. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46672. }
  46673. else {
  46674. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46675. }
  46676. };
  46677. /**
  46678. * 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)
  46679. * @returns the current camera
  46680. */
  46681. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46682. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46683. return this;
  46684. };
  46685. /** @hidden */
  46686. TargetCamera.prototype._getViewMatrix = function () {
  46687. if (this.lockedTarget) {
  46688. this.setTarget(this._getLockedTargetPosition());
  46689. }
  46690. // Compute
  46691. this._updateCameraRotationMatrix();
  46692. // Apply the changed rotation to the upVector.
  46693. if (this._cachedRotationZ != this.rotation.z) {
  46694. this._rotateUpVectorWithCameraRotationMatrix();
  46695. this._cachedRotationZ = this.rotation.z;
  46696. }
  46697. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46698. // Computing target and final matrix
  46699. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46700. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46701. return this._viewMatrix;
  46702. };
  46703. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46704. if (this.parent) {
  46705. var parentWorldMatrix = this.parent.getWorldMatrix();
  46706. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46707. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46708. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46709. this._markSyncedWithParent();
  46710. }
  46711. else {
  46712. this._globalPosition.copyFrom(position);
  46713. this._globalCurrentTarget.copyFrom(target);
  46714. this._globalCurrentUpVector.copyFrom(up);
  46715. }
  46716. if (this.getScene().useRightHandedSystem) {
  46717. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46718. }
  46719. else {
  46720. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46721. }
  46722. };
  46723. /**
  46724. * @override
  46725. * Override Camera.createRigCamera
  46726. */
  46727. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46728. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46729. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46730. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46731. if (!this.rotationQuaternion) {
  46732. this.rotationQuaternion = new BABYLON.Quaternion();
  46733. }
  46734. rigCamera._cameraRigParams = {};
  46735. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46736. }
  46737. return rigCamera;
  46738. }
  46739. return null;
  46740. };
  46741. /**
  46742. * @hidden
  46743. * @override
  46744. * Override Camera._updateRigCameras
  46745. */
  46746. TargetCamera.prototype._updateRigCameras = function () {
  46747. var camLeft = this._rigCameras[0];
  46748. var camRight = this._rigCameras[1];
  46749. switch (this.cameraRigMode) {
  46750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46753. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46754. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46755. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46756. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46757. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46758. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46759. camLeft.setTarget(this.getTarget());
  46760. camRight.setTarget(this.getTarget());
  46761. break;
  46762. case BABYLON.Camera.RIG_MODE_VR:
  46763. if (camLeft.rotationQuaternion) {
  46764. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46765. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46766. }
  46767. else {
  46768. camLeft.rotation.copyFrom(this.rotation);
  46769. camRight.rotation.copyFrom(this.rotation);
  46770. }
  46771. camLeft.position.copyFrom(this.position);
  46772. camRight.position.copyFrom(this.position);
  46773. break;
  46774. }
  46775. _super.prototype._updateRigCameras.call(this);
  46776. };
  46777. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46778. if (!this._rigCamTransformMatrix) {
  46779. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46780. }
  46781. var target = this.getTarget();
  46782. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46783. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46784. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46785. };
  46786. TargetCamera.prototype.getClassName = function () {
  46787. return "TargetCamera";
  46788. };
  46789. __decorate([
  46790. BABYLON.serializeAsVector3()
  46791. ], TargetCamera.prototype, "rotation", void 0);
  46792. __decorate([
  46793. BABYLON.serialize()
  46794. ], TargetCamera.prototype, "speed", void 0);
  46795. __decorate([
  46796. BABYLON.serializeAsMeshReference("lockedTargetId")
  46797. ], TargetCamera.prototype, "lockedTarget", void 0);
  46798. return TargetCamera;
  46799. }(BABYLON.Camera));
  46800. BABYLON.TargetCamera = TargetCamera;
  46801. })(BABYLON || (BABYLON = {}));
  46802. //# sourceMappingURL=babylon.targetCamera.js.map
  46803. var BABYLON;
  46804. (function (BABYLON) {
  46805. var FreeCameraMouseInput = /** @class */ (function () {
  46806. function FreeCameraMouseInput(touchEnabled) {
  46807. if (touchEnabled === void 0) { touchEnabled = true; }
  46808. this.touchEnabled = touchEnabled;
  46809. this.buttons = [0, 1, 2];
  46810. this.angularSensibility = 2000.0;
  46811. this.previousPosition = null;
  46812. }
  46813. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46814. var _this = this;
  46815. var engine = this.camera.getEngine();
  46816. if (!this._pointerInput) {
  46817. this._pointerInput = function (p, s) {
  46818. var evt = p.event;
  46819. if (engine.isInVRExclusivePointerMode) {
  46820. return;
  46821. }
  46822. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46823. return;
  46824. }
  46825. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46826. return;
  46827. }
  46828. var srcElement = (evt.srcElement || evt.target);
  46829. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46830. try {
  46831. srcElement.setPointerCapture(evt.pointerId);
  46832. }
  46833. catch (e) {
  46834. //Nothing to do with the error. Execution will continue.
  46835. }
  46836. _this.previousPosition = {
  46837. x: evt.clientX,
  46838. y: evt.clientY
  46839. };
  46840. if (!noPreventDefault) {
  46841. evt.preventDefault();
  46842. element.focus();
  46843. }
  46844. }
  46845. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46846. try {
  46847. srcElement.releasePointerCapture(evt.pointerId);
  46848. }
  46849. catch (e) {
  46850. //Nothing to do with the error.
  46851. }
  46852. _this.previousPosition = null;
  46853. if (!noPreventDefault) {
  46854. evt.preventDefault();
  46855. }
  46856. }
  46857. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46858. if (!_this.previousPosition || engine.isPointerLock) {
  46859. return;
  46860. }
  46861. var offsetX = evt.clientX - _this.previousPosition.x;
  46862. if (_this.camera.getScene().useRightHandedSystem)
  46863. offsetX *= -1;
  46864. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46865. offsetX *= -1;
  46866. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46867. var offsetY = evt.clientY - _this.previousPosition.y;
  46868. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46869. _this.previousPosition = {
  46870. x: evt.clientX,
  46871. y: evt.clientY
  46872. };
  46873. if (!noPreventDefault) {
  46874. evt.preventDefault();
  46875. }
  46876. }
  46877. };
  46878. }
  46879. this._onMouseMove = function (evt) {
  46880. if (!engine.isPointerLock) {
  46881. return;
  46882. }
  46883. if (engine.isInVRExclusivePointerMode) {
  46884. return;
  46885. }
  46886. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46887. if (_this.camera.getScene().useRightHandedSystem)
  46888. offsetX *= -1;
  46889. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46890. offsetX *= -1;
  46891. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46892. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46893. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46894. _this.previousPosition = null;
  46895. if (!noPreventDefault) {
  46896. evt.preventDefault();
  46897. }
  46898. };
  46899. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46900. element.addEventListener("mousemove", this._onMouseMove, false);
  46901. };
  46902. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46903. if (this._observer && element) {
  46904. this.camera.getScene().onPointerObservable.remove(this._observer);
  46905. if (this._onMouseMove) {
  46906. element.removeEventListener("mousemove", this._onMouseMove);
  46907. }
  46908. this._observer = null;
  46909. this._onMouseMove = null;
  46910. this.previousPosition = null;
  46911. }
  46912. };
  46913. FreeCameraMouseInput.prototype.getClassName = function () {
  46914. return "FreeCameraMouseInput";
  46915. };
  46916. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46917. return "mouse";
  46918. };
  46919. __decorate([
  46920. BABYLON.serialize()
  46921. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46922. __decorate([
  46923. BABYLON.serialize()
  46924. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46925. return FreeCameraMouseInput;
  46926. }());
  46927. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46928. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46929. })(BABYLON || (BABYLON = {}));
  46930. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46931. var BABYLON;
  46932. (function (BABYLON) {
  46933. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46934. function FreeCameraKeyboardMoveInput() {
  46935. this._keys = new Array();
  46936. this.keysUp = [38];
  46937. this.keysDown = [40];
  46938. this.keysLeft = [37];
  46939. this.keysRight = [39];
  46940. }
  46941. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46942. var _this = this;
  46943. if (this._onCanvasBlurObserver) {
  46944. return;
  46945. }
  46946. this._scene = this.camera.getScene();
  46947. this._engine = this._scene.getEngine();
  46948. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46949. _this._keys = [];
  46950. });
  46951. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46952. var evt = info.event;
  46953. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46954. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46955. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46956. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46957. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46958. var index = _this._keys.indexOf(evt.keyCode);
  46959. if (index === -1) {
  46960. _this._keys.push(evt.keyCode);
  46961. }
  46962. if (!noPreventDefault) {
  46963. evt.preventDefault();
  46964. }
  46965. }
  46966. }
  46967. else {
  46968. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46969. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46970. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46971. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46972. var index = _this._keys.indexOf(evt.keyCode);
  46973. if (index >= 0) {
  46974. _this._keys.splice(index, 1);
  46975. }
  46976. if (!noPreventDefault) {
  46977. evt.preventDefault();
  46978. }
  46979. }
  46980. }
  46981. });
  46982. };
  46983. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46984. if (this._scene) {
  46985. if (this._onKeyboardObserver) {
  46986. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46987. }
  46988. if (this._onCanvasBlurObserver) {
  46989. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46990. }
  46991. this._onKeyboardObserver = null;
  46992. this._onCanvasBlurObserver = null;
  46993. }
  46994. this._keys = [];
  46995. };
  46996. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46997. if (this._onKeyboardObserver) {
  46998. var camera = this.camera;
  46999. // Keyboard
  47000. for (var index = 0; index < this._keys.length; index++) {
  47001. var keyCode = this._keys[index];
  47002. var speed = camera._computeLocalCameraSpeed();
  47003. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47004. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47005. }
  47006. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47007. camera._localDirection.copyFromFloats(0, 0, speed);
  47008. }
  47009. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47010. camera._localDirection.copyFromFloats(speed, 0, 0);
  47011. }
  47012. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47013. camera._localDirection.copyFromFloats(0, 0, -speed);
  47014. }
  47015. if (camera.getScene().useRightHandedSystem) {
  47016. camera._localDirection.z *= -1;
  47017. }
  47018. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47019. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47020. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47021. }
  47022. }
  47023. };
  47024. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47025. return "FreeCameraKeyboardMoveInput";
  47026. };
  47027. /** @hidden */
  47028. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47029. this._keys = [];
  47030. };
  47031. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47032. return "keyboard";
  47033. };
  47034. __decorate([
  47035. BABYLON.serialize()
  47036. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47037. __decorate([
  47038. BABYLON.serialize()
  47039. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47040. __decorate([
  47041. BABYLON.serialize()
  47042. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47043. __decorate([
  47044. BABYLON.serialize()
  47045. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47046. return FreeCameraKeyboardMoveInput;
  47047. }());
  47048. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47049. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47050. })(BABYLON || (BABYLON = {}));
  47051. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47052. var BABYLON;
  47053. (function (BABYLON) {
  47054. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47055. __extends(FreeCameraInputsManager, _super);
  47056. function FreeCameraInputsManager(camera) {
  47057. return _super.call(this, camera) || this;
  47058. }
  47059. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47060. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47061. return this;
  47062. };
  47063. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47064. if (touchEnabled === void 0) { touchEnabled = true; }
  47065. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47066. return this;
  47067. };
  47068. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47069. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47070. return this;
  47071. };
  47072. FreeCameraInputsManager.prototype.addTouch = function () {
  47073. this.add(new BABYLON.FreeCameraTouchInput());
  47074. return this;
  47075. };
  47076. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47077. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47078. return this;
  47079. };
  47080. return FreeCameraInputsManager;
  47081. }(BABYLON.CameraInputsManager));
  47082. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47083. })(BABYLON || (BABYLON = {}));
  47084. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47085. var BABYLON;
  47086. (function (BABYLON) {
  47087. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47088. // Forcing to use the Universal camera
  47089. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47090. });
  47091. var FreeCamera = /** @class */ (function (_super) {
  47092. __extends(FreeCamera, _super);
  47093. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47094. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47095. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47096. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47097. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47098. _this.checkCollisions = false;
  47099. _this.applyGravity = false;
  47100. _this._needMoveForGravity = false;
  47101. _this._oldPosition = BABYLON.Vector3.Zero();
  47102. _this._diffPosition = BABYLON.Vector3.Zero();
  47103. _this._newPosition = BABYLON.Vector3.Zero();
  47104. // Collisions
  47105. _this._collisionMask = -1;
  47106. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47107. if (collidedMesh === void 0) { collidedMesh = null; }
  47108. //TODO move this to the collision coordinator!
  47109. if (_this.getScene().workerCollisions)
  47110. newPosition.multiplyInPlace(_this._collider._radius);
  47111. var updatePosition = function (newPos) {
  47112. _this._newPosition.copyFrom(newPos);
  47113. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47114. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47115. _this.position.addInPlace(_this._diffPosition);
  47116. if (_this.onCollide && collidedMesh) {
  47117. _this.onCollide(collidedMesh);
  47118. }
  47119. }
  47120. };
  47121. updatePosition(newPosition);
  47122. };
  47123. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47124. _this.inputs.addKeyboard().addMouse();
  47125. return _this;
  47126. }
  47127. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47128. //-- begin properties for backward compatibility for inputs
  47129. /**
  47130. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47131. * Higher values reduce sensitivity.
  47132. */
  47133. get: function () {
  47134. var mouse = this.inputs.attached["mouse"];
  47135. if (mouse)
  47136. return mouse.angularSensibility;
  47137. return 0;
  47138. },
  47139. /**
  47140. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47141. * Higher values reduce sensitivity.
  47142. */
  47143. set: function (value) {
  47144. var mouse = this.inputs.attached["mouse"];
  47145. if (mouse)
  47146. mouse.angularSensibility = value;
  47147. },
  47148. enumerable: true,
  47149. configurable: true
  47150. });
  47151. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47152. get: function () {
  47153. var keyboard = this.inputs.attached["keyboard"];
  47154. if (keyboard)
  47155. return keyboard.keysUp;
  47156. return [];
  47157. },
  47158. set: function (value) {
  47159. var keyboard = this.inputs.attached["keyboard"];
  47160. if (keyboard)
  47161. keyboard.keysUp = value;
  47162. },
  47163. enumerable: true,
  47164. configurable: true
  47165. });
  47166. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47167. get: function () {
  47168. var keyboard = this.inputs.attached["keyboard"];
  47169. if (keyboard)
  47170. return keyboard.keysDown;
  47171. return [];
  47172. },
  47173. set: function (value) {
  47174. var keyboard = this.inputs.attached["keyboard"];
  47175. if (keyboard)
  47176. keyboard.keysDown = value;
  47177. },
  47178. enumerable: true,
  47179. configurable: true
  47180. });
  47181. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47182. get: function () {
  47183. var keyboard = this.inputs.attached["keyboard"];
  47184. if (keyboard)
  47185. return keyboard.keysLeft;
  47186. return [];
  47187. },
  47188. set: function (value) {
  47189. var keyboard = this.inputs.attached["keyboard"];
  47190. if (keyboard)
  47191. keyboard.keysLeft = value;
  47192. },
  47193. enumerable: true,
  47194. configurable: true
  47195. });
  47196. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47197. get: function () {
  47198. var keyboard = this.inputs.attached["keyboard"];
  47199. if (keyboard)
  47200. return keyboard.keysRight;
  47201. return [];
  47202. },
  47203. set: function (value) {
  47204. var keyboard = this.inputs.attached["keyboard"];
  47205. if (keyboard)
  47206. keyboard.keysRight = value;
  47207. },
  47208. enumerable: true,
  47209. configurable: true
  47210. });
  47211. // Controls
  47212. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47213. this.inputs.attachElement(element, noPreventDefault);
  47214. };
  47215. FreeCamera.prototype.detachControl = function (element) {
  47216. this.inputs.detachElement(element);
  47217. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47218. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47219. };
  47220. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47221. get: function () {
  47222. return this._collisionMask;
  47223. },
  47224. set: function (mask) {
  47225. this._collisionMask = !isNaN(mask) ? mask : -1;
  47226. },
  47227. enumerable: true,
  47228. configurable: true
  47229. });
  47230. /** @hidden */
  47231. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47232. var globalPosition;
  47233. if (this.parent) {
  47234. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47235. }
  47236. else {
  47237. globalPosition = this.position;
  47238. }
  47239. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47240. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47241. if (!this._collider) {
  47242. this._collider = new BABYLON.Collider();
  47243. }
  47244. this._collider._radius = this.ellipsoid;
  47245. this._collider.collisionMask = this._collisionMask;
  47246. //no need for clone, as long as gravity is not on.
  47247. var actualDisplacement = displacement;
  47248. //add gravity to the direction to prevent the dual-collision checking
  47249. if (this.applyGravity) {
  47250. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47251. actualDisplacement = displacement.add(this.getScene().gravity);
  47252. }
  47253. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47254. };
  47255. /** @hidden */
  47256. FreeCamera.prototype._checkInputs = function () {
  47257. if (!this._localDirection) {
  47258. this._localDirection = BABYLON.Vector3.Zero();
  47259. this._transformedDirection = BABYLON.Vector3.Zero();
  47260. }
  47261. this.inputs.checkInputs();
  47262. _super.prototype._checkInputs.call(this);
  47263. };
  47264. /** @hidden */
  47265. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47266. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47267. };
  47268. /** @hidden */
  47269. FreeCamera.prototype._updatePosition = function () {
  47270. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47271. this._collideWithWorld(this.cameraDirection);
  47272. }
  47273. else {
  47274. _super.prototype._updatePosition.call(this);
  47275. }
  47276. };
  47277. FreeCamera.prototype.dispose = function () {
  47278. this.inputs.clear();
  47279. _super.prototype.dispose.call(this);
  47280. };
  47281. FreeCamera.prototype.getClassName = function () {
  47282. return "FreeCamera";
  47283. };
  47284. __decorate([
  47285. BABYLON.serializeAsVector3()
  47286. ], FreeCamera.prototype, "ellipsoid", void 0);
  47287. __decorate([
  47288. BABYLON.serializeAsVector3()
  47289. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47290. __decorate([
  47291. BABYLON.serialize()
  47292. ], FreeCamera.prototype, "checkCollisions", void 0);
  47293. __decorate([
  47294. BABYLON.serialize()
  47295. ], FreeCamera.prototype, "applyGravity", void 0);
  47296. return FreeCamera;
  47297. }(BABYLON.TargetCamera));
  47298. BABYLON.FreeCamera = FreeCamera;
  47299. })(BABYLON || (BABYLON = {}));
  47300. //# sourceMappingURL=babylon.freeCamera.js.map
  47301. var BABYLON;
  47302. (function (BABYLON) {
  47303. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47304. function ArcRotateCameraKeyboardMoveInput() {
  47305. this._keys = new Array();
  47306. this.keysUp = [38];
  47307. this.keysDown = [40];
  47308. this.keysLeft = [37];
  47309. this.keysRight = [39];
  47310. this.keysReset = [220];
  47311. this.panningSensibility = 50.0;
  47312. this.zoomingSensibility = 25.0;
  47313. this.useAltToZoom = true;
  47314. }
  47315. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47316. var _this = this;
  47317. if (this._onCanvasBlurObserver) {
  47318. return;
  47319. }
  47320. this._scene = this.camera.getScene();
  47321. this._engine = this._scene.getEngine();
  47322. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47323. _this._keys = [];
  47324. });
  47325. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47326. var evt = info.event;
  47327. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47328. _this._ctrlPressed = evt.ctrlKey;
  47329. _this._altPressed = evt.altKey;
  47330. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47331. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47332. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47333. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47334. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47335. var index = _this._keys.indexOf(evt.keyCode);
  47336. if (index === -1) {
  47337. _this._keys.push(evt.keyCode);
  47338. }
  47339. if (evt.preventDefault) {
  47340. if (!noPreventDefault) {
  47341. evt.preventDefault();
  47342. }
  47343. }
  47344. }
  47345. }
  47346. else {
  47347. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47348. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47349. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47350. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47351. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47352. var index = _this._keys.indexOf(evt.keyCode);
  47353. if (index >= 0) {
  47354. _this._keys.splice(index, 1);
  47355. }
  47356. if (evt.preventDefault) {
  47357. if (!noPreventDefault) {
  47358. evt.preventDefault();
  47359. }
  47360. }
  47361. }
  47362. }
  47363. });
  47364. };
  47365. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47366. if (this._scene) {
  47367. if (this._onKeyboardObserver) {
  47368. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47369. }
  47370. if (this._onCanvasBlurObserver) {
  47371. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47372. }
  47373. this._onKeyboardObserver = null;
  47374. this._onCanvasBlurObserver = null;
  47375. }
  47376. this._keys = [];
  47377. };
  47378. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47379. if (this._onKeyboardObserver) {
  47380. var camera = this.camera;
  47381. for (var index = 0; index < this._keys.length; index++) {
  47382. var keyCode = this._keys[index];
  47383. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47384. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47385. camera.inertialPanningX -= 1 / this.panningSensibility;
  47386. }
  47387. else {
  47388. camera.inertialAlphaOffset -= 0.01;
  47389. }
  47390. }
  47391. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47392. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47393. camera.inertialPanningY += 1 / this.panningSensibility;
  47394. }
  47395. else if (this._altPressed && this.useAltToZoom) {
  47396. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47397. }
  47398. else {
  47399. camera.inertialBetaOffset -= 0.01;
  47400. }
  47401. }
  47402. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47403. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47404. camera.inertialPanningX += 1 / this.panningSensibility;
  47405. }
  47406. else {
  47407. camera.inertialAlphaOffset += 0.01;
  47408. }
  47409. }
  47410. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47411. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47412. camera.inertialPanningY -= 1 / this.panningSensibility;
  47413. }
  47414. else if (this._altPressed && this.useAltToZoom) {
  47415. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47416. }
  47417. else {
  47418. camera.inertialBetaOffset += 0.01;
  47419. }
  47420. }
  47421. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47422. camera.restoreState();
  47423. }
  47424. }
  47425. }
  47426. };
  47427. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47428. return "ArcRotateCameraKeyboardMoveInput";
  47429. };
  47430. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47431. return "keyboard";
  47432. };
  47433. __decorate([
  47434. BABYLON.serialize()
  47435. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47436. __decorate([
  47437. BABYLON.serialize()
  47438. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47439. __decorate([
  47440. BABYLON.serialize()
  47441. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47442. __decorate([
  47443. BABYLON.serialize()
  47444. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47445. __decorate([
  47446. BABYLON.serialize()
  47447. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47448. __decorate([
  47449. BABYLON.serialize()
  47450. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47451. __decorate([
  47452. BABYLON.serialize()
  47453. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47454. __decorate([
  47455. BABYLON.serialize()
  47456. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47457. return ArcRotateCameraKeyboardMoveInput;
  47458. }());
  47459. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47460. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47461. })(BABYLON || (BABYLON = {}));
  47462. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47463. var BABYLON;
  47464. (function (BABYLON) {
  47465. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47466. function ArcRotateCameraMouseWheelInput() {
  47467. this.wheelPrecision = 3.0;
  47468. /**
  47469. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47470. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47471. */
  47472. this.wheelDeltaPercentage = 0;
  47473. }
  47474. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47475. var _this = this;
  47476. this._wheel = function (p, s) {
  47477. //sanity check - this should be a PointerWheel event.
  47478. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47479. return;
  47480. var event = p.event;
  47481. var delta = 0;
  47482. if (event.wheelDelta) {
  47483. if (_this.wheelDeltaPercentage) {
  47484. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47485. if (event.wheelDelta > 0) {
  47486. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47487. }
  47488. else {
  47489. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47490. }
  47491. }
  47492. else {
  47493. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47494. }
  47495. }
  47496. else if (event.detail) {
  47497. delta = -event.detail / _this.wheelPrecision;
  47498. }
  47499. if (delta)
  47500. _this.camera.inertialRadiusOffset += delta;
  47501. if (event.preventDefault) {
  47502. if (!noPreventDefault) {
  47503. event.preventDefault();
  47504. }
  47505. }
  47506. };
  47507. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47508. };
  47509. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47510. if (this._observer && element) {
  47511. this.camera.getScene().onPointerObservable.remove(this._observer);
  47512. this._observer = null;
  47513. this._wheel = null;
  47514. }
  47515. };
  47516. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47517. return "ArcRotateCameraMouseWheelInput";
  47518. };
  47519. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47520. return "mousewheel";
  47521. };
  47522. __decorate([
  47523. BABYLON.serialize()
  47524. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47525. __decorate([
  47526. BABYLON.serialize()
  47527. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47528. return ArcRotateCameraMouseWheelInput;
  47529. }());
  47530. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47531. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47532. })(BABYLON || (BABYLON = {}));
  47533. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47534. var BABYLON;
  47535. (function (BABYLON) {
  47536. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47537. function ArcRotateCameraPointersInput() {
  47538. this.buttons = [0, 1, 2];
  47539. this.angularSensibilityX = 1000.0;
  47540. this.angularSensibilityY = 1000.0;
  47541. this.pinchPrecision = 12.0;
  47542. /**
  47543. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47544. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47545. */
  47546. this.pinchDeltaPercentage = 0;
  47547. this.panningSensibility = 1000.0;
  47548. this.multiTouchPanning = true;
  47549. this.multiTouchPanAndZoom = true;
  47550. this._isPanClick = false;
  47551. this.pinchInwards = true;
  47552. }
  47553. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47554. var _this = this;
  47555. var engine = this.camera.getEngine();
  47556. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47557. var pointA = null;
  47558. var pointB = null;
  47559. var previousPinchSquaredDistance = 0;
  47560. var initialDistance = 0;
  47561. var twoFingerActivityCount = 0;
  47562. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47563. this._pointerInput = function (p, s) {
  47564. var evt = p.event;
  47565. var isTouch = p.event.pointerType === "touch";
  47566. if (engine.isInVRExclusivePointerMode) {
  47567. return;
  47568. }
  47569. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47570. return;
  47571. }
  47572. var srcElement = (evt.srcElement || evt.target);
  47573. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47574. try {
  47575. srcElement.setPointerCapture(evt.pointerId);
  47576. }
  47577. catch (e) {
  47578. //Nothing to do with the error. Execution will continue.
  47579. }
  47580. // Manage panning with pan button click
  47581. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47582. // manage pointers
  47583. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47584. if (pointA === null) {
  47585. pointA = cacheSoloPointer;
  47586. }
  47587. else if (pointB === null) {
  47588. pointB = cacheSoloPointer;
  47589. }
  47590. if (!noPreventDefault) {
  47591. evt.preventDefault();
  47592. element.focus();
  47593. }
  47594. }
  47595. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47596. _this.camera.restoreState();
  47597. }
  47598. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47599. try {
  47600. srcElement.releasePointerCapture(evt.pointerId);
  47601. }
  47602. catch (e) {
  47603. //Nothing to do with the error.
  47604. }
  47605. cacheSoloPointer = null;
  47606. previousPinchSquaredDistance = 0;
  47607. previousMultiTouchPanPosition.isPaning = false;
  47608. previousMultiTouchPanPosition.isPinching = false;
  47609. twoFingerActivityCount = 0;
  47610. initialDistance = 0;
  47611. if (!isTouch) {
  47612. pointB = null; // Mouse and pen are mono pointer
  47613. }
  47614. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47615. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47616. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47617. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47618. if (engine._badOS) {
  47619. pointA = pointB = null;
  47620. }
  47621. else {
  47622. //only remove the impacted pointer in case of multitouch allowing on most
  47623. //platforms switching from rotate to zoom and pan seamlessly.
  47624. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47625. pointA = pointB;
  47626. pointB = null;
  47627. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47628. }
  47629. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47630. pointB = null;
  47631. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47632. }
  47633. else {
  47634. pointA = pointB = null;
  47635. }
  47636. }
  47637. if (!noPreventDefault) {
  47638. evt.preventDefault();
  47639. }
  47640. }
  47641. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47642. if (!noPreventDefault) {
  47643. evt.preventDefault();
  47644. }
  47645. // One button down
  47646. if (pointA && pointB === null && cacheSoloPointer) {
  47647. if (_this.panningSensibility !== 0 &&
  47648. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47649. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47650. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47651. }
  47652. else {
  47653. var offsetX = evt.clientX - cacheSoloPointer.x;
  47654. var offsetY = evt.clientY - cacheSoloPointer.y;
  47655. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47656. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47657. }
  47658. cacheSoloPointer.x = evt.clientX;
  47659. cacheSoloPointer.y = evt.clientY;
  47660. }
  47661. // Two buttons down: pinch/pan
  47662. else if (pointA && pointB) {
  47663. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47664. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47665. ed.x = evt.clientX;
  47666. ed.y = evt.clientY;
  47667. var direction = _this.pinchInwards ? 1 : -1;
  47668. var distX = pointA.x - pointB.x;
  47669. var distY = pointA.y - pointB.y;
  47670. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47671. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47672. if (previousPinchSquaredDistance === 0) {
  47673. initialDistance = pinchDistance;
  47674. previousPinchSquaredDistance = pinchSquaredDistance;
  47675. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47676. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47677. return;
  47678. }
  47679. if (_this.multiTouchPanAndZoom) {
  47680. if (_this.pinchDeltaPercentage) {
  47681. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47682. }
  47683. else {
  47684. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47685. (_this.pinchPrecision *
  47686. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47687. direction);
  47688. }
  47689. if (_this.panningSensibility !== 0) {
  47690. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47691. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47692. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47693. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47694. previousMultiTouchPanPosition.x = pointersCenterX;
  47695. previousMultiTouchPanPosition.y = pointersCenterY;
  47696. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47697. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47698. }
  47699. }
  47700. else {
  47701. twoFingerActivityCount++;
  47702. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47703. if (_this.pinchDeltaPercentage) {
  47704. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47705. }
  47706. else {
  47707. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47708. (_this.pinchPrecision *
  47709. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47710. direction);
  47711. }
  47712. previousMultiTouchPanPosition.isPaning = false;
  47713. previousMultiTouchPanPosition.isPinching = true;
  47714. }
  47715. else {
  47716. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47717. if (!previousMultiTouchPanPosition.isPaning) {
  47718. previousMultiTouchPanPosition.isPaning = true;
  47719. previousMultiTouchPanPosition.isPinching = false;
  47720. previousMultiTouchPanPosition.x = ed.x;
  47721. previousMultiTouchPanPosition.y = ed.y;
  47722. return;
  47723. }
  47724. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47725. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47726. }
  47727. }
  47728. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47729. previousMultiTouchPanPosition.x = ed.x;
  47730. previousMultiTouchPanPosition.y = ed.y;
  47731. }
  47732. }
  47733. previousPinchSquaredDistance = pinchSquaredDistance;
  47734. }
  47735. }
  47736. };
  47737. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47738. this._onContextMenu = function (evt) {
  47739. evt.preventDefault();
  47740. };
  47741. if (!this.camera._useCtrlForPanning) {
  47742. element.addEventListener("contextmenu", this._onContextMenu, false);
  47743. }
  47744. this._onLostFocus = function () {
  47745. //this._keys = [];
  47746. pointA = pointB = null;
  47747. previousPinchSquaredDistance = 0;
  47748. previousMultiTouchPanPosition.isPaning = false;
  47749. previousMultiTouchPanPosition.isPinching = false;
  47750. twoFingerActivityCount = 0;
  47751. cacheSoloPointer = null;
  47752. initialDistance = 0;
  47753. };
  47754. this._onMouseMove = function (evt) {
  47755. if (!engine.isPointerLock) {
  47756. return;
  47757. }
  47758. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47759. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47760. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47761. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47762. if (!noPreventDefault) {
  47763. evt.preventDefault();
  47764. }
  47765. };
  47766. this._onGestureStart = function (e) {
  47767. if (window.MSGesture === undefined) {
  47768. return;
  47769. }
  47770. if (!_this._MSGestureHandler) {
  47771. _this._MSGestureHandler = new MSGesture();
  47772. _this._MSGestureHandler.target = element;
  47773. }
  47774. _this._MSGestureHandler.addPointer(e.pointerId);
  47775. };
  47776. this._onGesture = function (e) {
  47777. _this.camera.radius *= e.scale;
  47778. if (e.preventDefault) {
  47779. if (!noPreventDefault) {
  47780. e.stopPropagation();
  47781. e.preventDefault();
  47782. }
  47783. }
  47784. };
  47785. element.addEventListener("mousemove", this._onMouseMove, false);
  47786. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47787. element.addEventListener("MSGestureChange", this._onGesture, false);
  47788. BABYLON.Tools.RegisterTopRootEvents([
  47789. { name: "blur", handler: this._onLostFocus }
  47790. ]);
  47791. };
  47792. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47793. if (this._onLostFocus) {
  47794. BABYLON.Tools.UnregisterTopRootEvents([
  47795. { name: "blur", handler: this._onLostFocus }
  47796. ]);
  47797. }
  47798. if (element && this._observer) {
  47799. this.camera.getScene().onPointerObservable.remove(this._observer);
  47800. this._observer = null;
  47801. if (this._onContextMenu) {
  47802. element.removeEventListener("contextmenu", this._onContextMenu);
  47803. }
  47804. if (this._onMouseMove) {
  47805. element.removeEventListener("mousemove", this._onMouseMove);
  47806. }
  47807. if (this._onGestureStart) {
  47808. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47809. }
  47810. if (this._onGesture) {
  47811. element.removeEventListener("MSGestureChange", this._onGesture);
  47812. }
  47813. this._isPanClick = false;
  47814. this.pinchInwards = true;
  47815. this._onMouseMove = null;
  47816. this._onGestureStart = null;
  47817. this._onGesture = null;
  47818. this._MSGestureHandler = null;
  47819. this._onLostFocus = null;
  47820. this._onContextMenu = null;
  47821. }
  47822. };
  47823. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47824. return "ArcRotateCameraPointersInput";
  47825. };
  47826. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47827. return "pointers";
  47828. };
  47829. __decorate([
  47830. BABYLON.serialize()
  47831. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47832. __decorate([
  47833. BABYLON.serialize()
  47834. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47835. __decorate([
  47836. BABYLON.serialize()
  47837. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47838. __decorate([
  47839. BABYLON.serialize()
  47840. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47841. __decorate([
  47842. BABYLON.serialize()
  47843. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47844. __decorate([
  47845. BABYLON.serialize()
  47846. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47847. __decorate([
  47848. BABYLON.serialize()
  47849. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47850. __decorate([
  47851. BABYLON.serialize()
  47852. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47853. return ArcRotateCameraPointersInput;
  47854. }());
  47855. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47856. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47857. })(BABYLON || (BABYLON = {}));
  47858. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47859. var BABYLON;
  47860. (function (BABYLON) {
  47861. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47862. __extends(ArcRotateCameraInputsManager, _super);
  47863. function ArcRotateCameraInputsManager(camera) {
  47864. return _super.call(this, camera) || this;
  47865. }
  47866. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47867. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47868. return this;
  47869. };
  47870. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47871. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47872. return this;
  47873. };
  47874. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47875. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47876. return this;
  47877. };
  47878. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47879. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47880. return this;
  47881. };
  47882. return ArcRotateCameraInputsManager;
  47883. }(BABYLON.CameraInputsManager));
  47884. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47885. })(BABYLON || (BABYLON = {}));
  47886. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47887. var BABYLON;
  47888. (function (BABYLON) {
  47889. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47890. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47891. });
  47892. var ArcRotateCamera = /** @class */ (function (_super) {
  47893. __extends(ArcRotateCamera, _super);
  47894. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47895. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47896. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47897. _this.inertialAlphaOffset = 0;
  47898. _this.inertialBetaOffset = 0;
  47899. _this.inertialRadiusOffset = 0;
  47900. _this.lowerAlphaLimit = null;
  47901. _this.upperAlphaLimit = null;
  47902. _this.lowerBetaLimit = 0.01;
  47903. _this.upperBetaLimit = Math.PI;
  47904. _this.lowerRadiusLimit = null;
  47905. _this.upperRadiusLimit = null;
  47906. _this.inertialPanningX = 0;
  47907. _this.inertialPanningY = 0;
  47908. _this.pinchToPanMaxDistance = 20;
  47909. _this.panningDistanceLimit = null;
  47910. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47911. _this.panningInertia = 0.9;
  47912. //-- end properties for backward compatibility for inputs
  47913. _this.zoomOnFactor = 1;
  47914. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47915. _this.allowUpsideDown = true;
  47916. /** @hidden */
  47917. _this._viewMatrix = new BABYLON.Matrix();
  47918. // Panning
  47919. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47920. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47921. _this.checkCollisions = false;
  47922. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47923. _this._previousPosition = BABYLON.Vector3.Zero();
  47924. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47925. _this._newPosition = BABYLON.Vector3.Zero();
  47926. _this._computationVector = BABYLON.Vector3.Zero();
  47927. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47928. if (collidedMesh === void 0) { collidedMesh = null; }
  47929. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47930. newPosition.multiplyInPlace(_this._collider._radius);
  47931. }
  47932. if (!collidedMesh) {
  47933. _this._previousPosition.copyFrom(_this.position);
  47934. }
  47935. else {
  47936. _this.setPosition(newPosition);
  47937. if (_this.onCollide) {
  47938. _this.onCollide(collidedMesh);
  47939. }
  47940. }
  47941. // Recompute because of constraints
  47942. var cosa = Math.cos(_this.alpha);
  47943. var sina = Math.sin(_this.alpha);
  47944. var cosb = Math.cos(_this.beta);
  47945. var sinb = Math.sin(_this.beta);
  47946. if (sinb === 0) {
  47947. sinb = 0.0001;
  47948. }
  47949. var target = _this._getTargetPosition();
  47950. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47951. target.addToRef(_this._computationVector, _this._newPosition);
  47952. _this.position.copyFrom(_this._newPosition);
  47953. var up = _this.upVector;
  47954. if (_this.allowUpsideDown && _this.beta < 0) {
  47955. up = up.clone();
  47956. up = up.negate();
  47957. }
  47958. _this._computeViewMatrix(_this.position, target, up);
  47959. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47960. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47961. _this._collisionTriggered = false;
  47962. };
  47963. _this._target = BABYLON.Vector3.Zero();
  47964. if (target) {
  47965. _this.setTarget(target);
  47966. }
  47967. _this.alpha = alpha;
  47968. _this.beta = beta;
  47969. _this.radius = radius;
  47970. _this.getViewMatrix();
  47971. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47972. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47973. return _this;
  47974. }
  47975. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47976. get: function () {
  47977. return this._target;
  47978. },
  47979. set: function (value) {
  47980. this.setTarget(value);
  47981. },
  47982. enumerable: true,
  47983. configurable: true
  47984. });
  47985. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47986. //-- begin properties for backward compatibility for inputs
  47987. get: function () {
  47988. var pointers = this.inputs.attached["pointers"];
  47989. if (pointers)
  47990. return pointers.angularSensibilityX;
  47991. return 0;
  47992. },
  47993. set: function (value) {
  47994. var pointers = this.inputs.attached["pointers"];
  47995. if (pointers) {
  47996. pointers.angularSensibilityX = value;
  47997. }
  47998. },
  47999. enumerable: true,
  48000. configurable: true
  48001. });
  48002. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48003. get: function () {
  48004. var pointers = this.inputs.attached["pointers"];
  48005. if (pointers)
  48006. return pointers.angularSensibilityY;
  48007. return 0;
  48008. },
  48009. set: function (value) {
  48010. var pointers = this.inputs.attached["pointers"];
  48011. if (pointers) {
  48012. pointers.angularSensibilityY = value;
  48013. }
  48014. },
  48015. enumerable: true,
  48016. configurable: true
  48017. });
  48018. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48019. get: function () {
  48020. var pointers = this.inputs.attached["pointers"];
  48021. if (pointers)
  48022. return pointers.pinchPrecision;
  48023. return 0;
  48024. },
  48025. set: function (value) {
  48026. var pointers = this.inputs.attached["pointers"];
  48027. if (pointers) {
  48028. pointers.pinchPrecision = value;
  48029. }
  48030. },
  48031. enumerable: true,
  48032. configurable: true
  48033. });
  48034. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48035. get: function () {
  48036. var pointers = this.inputs.attached["pointers"];
  48037. if (pointers)
  48038. return pointers.pinchDeltaPercentage;
  48039. return 0;
  48040. },
  48041. set: function (value) {
  48042. var pointers = this.inputs.attached["pointers"];
  48043. if (pointers) {
  48044. pointers.pinchDeltaPercentage = value;
  48045. }
  48046. },
  48047. enumerable: true,
  48048. configurable: true
  48049. });
  48050. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48051. get: function () {
  48052. var pointers = this.inputs.attached["pointers"];
  48053. if (pointers)
  48054. return pointers.panningSensibility;
  48055. return 0;
  48056. },
  48057. set: function (value) {
  48058. var pointers = this.inputs.attached["pointers"];
  48059. if (pointers) {
  48060. pointers.panningSensibility = value;
  48061. }
  48062. },
  48063. enumerable: true,
  48064. configurable: true
  48065. });
  48066. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  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(ArcRotateCamera.prototype, "keysDown", {
  48082. get: function () {
  48083. var keyboard = this.inputs.attached["keyboard"];
  48084. if (keyboard)
  48085. return keyboard.keysDown;
  48086. return [];
  48087. },
  48088. set: function (value) {
  48089. var keyboard = this.inputs.attached["keyboard"];
  48090. if (keyboard)
  48091. keyboard.keysDown = value;
  48092. },
  48093. enumerable: true,
  48094. configurable: true
  48095. });
  48096. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48097. get: function () {
  48098. var keyboard = this.inputs.attached["keyboard"];
  48099. if (keyboard)
  48100. return keyboard.keysLeft;
  48101. return [];
  48102. },
  48103. set: function (value) {
  48104. var keyboard = this.inputs.attached["keyboard"];
  48105. if (keyboard)
  48106. keyboard.keysLeft = value;
  48107. },
  48108. enumerable: true,
  48109. configurable: true
  48110. });
  48111. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48112. get: function () {
  48113. var keyboard = this.inputs.attached["keyboard"];
  48114. if (keyboard)
  48115. return keyboard.keysRight;
  48116. return [];
  48117. },
  48118. set: function (value) {
  48119. var keyboard = this.inputs.attached["keyboard"];
  48120. if (keyboard)
  48121. keyboard.keysRight = value;
  48122. },
  48123. enumerable: true,
  48124. configurable: true
  48125. });
  48126. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48127. get: function () {
  48128. var mousewheel = this.inputs.attached["mousewheel"];
  48129. if (mousewheel)
  48130. return mousewheel.wheelPrecision;
  48131. return 0;
  48132. },
  48133. set: function (value) {
  48134. var mousewheel = this.inputs.attached["mousewheel"];
  48135. if (mousewheel)
  48136. mousewheel.wheelPrecision = value;
  48137. },
  48138. enumerable: true,
  48139. configurable: true
  48140. });
  48141. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48142. get: function () {
  48143. var mousewheel = this.inputs.attached["mousewheel"];
  48144. if (mousewheel)
  48145. return mousewheel.wheelDeltaPercentage;
  48146. return 0;
  48147. },
  48148. set: function (value) {
  48149. var mousewheel = this.inputs.attached["mousewheel"];
  48150. if (mousewheel)
  48151. mousewheel.wheelDeltaPercentage = value;
  48152. },
  48153. enumerable: true,
  48154. configurable: true
  48155. });
  48156. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48157. get: function () {
  48158. return this._bouncingBehavior;
  48159. },
  48160. enumerable: true,
  48161. configurable: true
  48162. });
  48163. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48164. get: function () {
  48165. return this._bouncingBehavior != null;
  48166. },
  48167. set: function (value) {
  48168. if (value === this.useBouncingBehavior) {
  48169. return;
  48170. }
  48171. if (value) {
  48172. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48173. this.addBehavior(this._bouncingBehavior);
  48174. }
  48175. else if (this._bouncingBehavior) {
  48176. this.removeBehavior(this._bouncingBehavior);
  48177. this._bouncingBehavior = null;
  48178. }
  48179. },
  48180. enumerable: true,
  48181. configurable: true
  48182. });
  48183. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48184. get: function () {
  48185. return this._framingBehavior;
  48186. },
  48187. enumerable: true,
  48188. configurable: true
  48189. });
  48190. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48191. get: function () {
  48192. return this._framingBehavior != null;
  48193. },
  48194. set: function (value) {
  48195. if (value === this.useFramingBehavior) {
  48196. return;
  48197. }
  48198. if (value) {
  48199. this._framingBehavior = new BABYLON.FramingBehavior();
  48200. this.addBehavior(this._framingBehavior);
  48201. }
  48202. else if (this._framingBehavior) {
  48203. this.removeBehavior(this._framingBehavior);
  48204. this._framingBehavior = null;
  48205. }
  48206. },
  48207. enumerable: true,
  48208. configurable: true
  48209. });
  48210. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48211. get: function () {
  48212. return this._autoRotationBehavior;
  48213. },
  48214. enumerable: true,
  48215. configurable: true
  48216. });
  48217. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48218. get: function () {
  48219. return this._autoRotationBehavior != null;
  48220. },
  48221. set: function (value) {
  48222. if (value === this.useAutoRotationBehavior) {
  48223. return;
  48224. }
  48225. if (value) {
  48226. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48227. this.addBehavior(this._autoRotationBehavior);
  48228. }
  48229. else if (this._autoRotationBehavior) {
  48230. this.removeBehavior(this._autoRotationBehavior);
  48231. this._autoRotationBehavior = null;
  48232. }
  48233. },
  48234. enumerable: true,
  48235. configurable: true
  48236. });
  48237. // Cache
  48238. /** @hidden */
  48239. ArcRotateCamera.prototype._initCache = function () {
  48240. _super.prototype._initCache.call(this);
  48241. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48242. this._cache.alpha = undefined;
  48243. this._cache.beta = undefined;
  48244. this._cache.radius = undefined;
  48245. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48246. };
  48247. /** @hidden */
  48248. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48249. if (!ignoreParentClass) {
  48250. _super.prototype._updateCache.call(this);
  48251. }
  48252. this._cache._target.copyFrom(this._getTargetPosition());
  48253. this._cache.alpha = this.alpha;
  48254. this._cache.beta = this.beta;
  48255. this._cache.radius = this.radius;
  48256. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48257. };
  48258. ArcRotateCamera.prototype._getTargetPosition = function () {
  48259. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48260. var pos = this._targetHost.getAbsolutePosition();
  48261. if (this._targetBoundingCenter) {
  48262. pos.addToRef(this._targetBoundingCenter, this._target);
  48263. }
  48264. else {
  48265. this._target.copyFrom(pos);
  48266. }
  48267. }
  48268. var lockedTargetPosition = this._getLockedTargetPosition();
  48269. if (lockedTargetPosition) {
  48270. return lockedTargetPosition;
  48271. }
  48272. return this._target;
  48273. };
  48274. ArcRotateCamera.prototype.storeState = function () {
  48275. this._storedAlpha = this.alpha;
  48276. this._storedBeta = this.beta;
  48277. this._storedRadius = this.radius;
  48278. this._storedTarget = this._getTargetPosition().clone();
  48279. return _super.prototype.storeState.call(this);
  48280. };
  48281. /**
  48282. * @hidden
  48283. * Restored camera state. You must call storeState() first
  48284. */
  48285. ArcRotateCamera.prototype._restoreStateValues = function () {
  48286. if (!_super.prototype._restoreStateValues.call(this)) {
  48287. return false;
  48288. }
  48289. this.alpha = this._storedAlpha;
  48290. this.beta = this._storedBeta;
  48291. this.radius = this._storedRadius;
  48292. this.setTarget(this._storedTarget.clone());
  48293. this.inertialAlphaOffset = 0;
  48294. this.inertialBetaOffset = 0;
  48295. this.inertialRadiusOffset = 0;
  48296. this.inertialPanningX = 0;
  48297. this.inertialPanningY = 0;
  48298. return true;
  48299. };
  48300. // Synchronized
  48301. /** @hidden */
  48302. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48303. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48304. return false;
  48305. return this._cache._target.equals(this._getTargetPosition())
  48306. && this._cache.alpha === this.alpha
  48307. && this._cache.beta === this.beta
  48308. && this._cache.radius === this.radius
  48309. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48310. };
  48311. // Methods
  48312. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48313. var _this = this;
  48314. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48315. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48316. this._useCtrlForPanning = useCtrlForPanning;
  48317. this._panningMouseButton = panningMouseButton;
  48318. this.inputs.attachElement(element, noPreventDefault);
  48319. this._reset = function () {
  48320. _this.inertialAlphaOffset = 0;
  48321. _this.inertialBetaOffset = 0;
  48322. _this.inertialRadiusOffset = 0;
  48323. _this.inertialPanningX = 0;
  48324. _this.inertialPanningY = 0;
  48325. };
  48326. };
  48327. ArcRotateCamera.prototype.detachControl = function (element) {
  48328. this.inputs.detachElement(element);
  48329. if (this._reset) {
  48330. this._reset();
  48331. }
  48332. };
  48333. /** @hidden */
  48334. ArcRotateCamera.prototype._checkInputs = function () {
  48335. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48336. if (this._collisionTriggered) {
  48337. return;
  48338. }
  48339. this.inputs.checkInputs();
  48340. // Inertia
  48341. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48342. var inertialAlphaOffset = this.inertialAlphaOffset;
  48343. if (this.beta <= 0)
  48344. inertialAlphaOffset *= -1;
  48345. if (this.getScene().useRightHandedSystem)
  48346. inertialAlphaOffset *= -1;
  48347. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48348. inertialAlphaOffset *= -1;
  48349. this.alpha += inertialAlphaOffset;
  48350. this.beta += this.inertialBetaOffset;
  48351. this.radius -= this.inertialRadiusOffset;
  48352. this.inertialAlphaOffset *= this.inertia;
  48353. this.inertialBetaOffset *= this.inertia;
  48354. this.inertialRadiusOffset *= this.inertia;
  48355. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48356. this.inertialAlphaOffset = 0;
  48357. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48358. this.inertialBetaOffset = 0;
  48359. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48360. this.inertialRadiusOffset = 0;
  48361. }
  48362. // Panning inertia
  48363. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48364. if (!this._localDirection) {
  48365. this._localDirection = BABYLON.Vector3.Zero();
  48366. this._transformedDirection = BABYLON.Vector3.Zero();
  48367. }
  48368. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48369. this._localDirection.multiplyInPlace(this.panningAxis);
  48370. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48371. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48372. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48373. if (!this.panningAxis.y) {
  48374. this._transformedDirection.y = 0;
  48375. }
  48376. if (!this._targetHost) {
  48377. if (this.panningDistanceLimit) {
  48378. this._transformedDirection.addInPlace(this._target);
  48379. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48380. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48381. this._target.copyFrom(this._transformedDirection);
  48382. }
  48383. }
  48384. else {
  48385. this._target.addInPlace(this._transformedDirection);
  48386. }
  48387. }
  48388. this.inertialPanningX *= this.panningInertia;
  48389. this.inertialPanningY *= this.panningInertia;
  48390. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48391. this.inertialPanningX = 0;
  48392. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48393. this.inertialPanningY = 0;
  48394. }
  48395. // Limits
  48396. this._checkLimits();
  48397. _super.prototype._checkInputs.call(this);
  48398. };
  48399. ArcRotateCamera.prototype._checkLimits = function () {
  48400. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48401. if (this.allowUpsideDown && this.beta > Math.PI) {
  48402. this.beta = this.beta - (2 * Math.PI);
  48403. }
  48404. }
  48405. else {
  48406. if (this.beta < this.lowerBetaLimit) {
  48407. this.beta = this.lowerBetaLimit;
  48408. }
  48409. }
  48410. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48411. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48412. this.beta = this.beta + (2 * Math.PI);
  48413. }
  48414. }
  48415. else {
  48416. if (this.beta > this.upperBetaLimit) {
  48417. this.beta = this.upperBetaLimit;
  48418. }
  48419. }
  48420. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48421. this.alpha = this.lowerAlphaLimit;
  48422. }
  48423. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48424. this.alpha = this.upperAlphaLimit;
  48425. }
  48426. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48427. this.radius = this.lowerRadiusLimit;
  48428. }
  48429. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48430. this.radius = this.upperRadiusLimit;
  48431. }
  48432. };
  48433. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48434. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48435. this.radius = this._computationVector.length();
  48436. if (this.radius === 0) {
  48437. this.radius = 0.0001; // Just to avoid division by zero
  48438. }
  48439. // Alpha
  48440. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48441. if (this._computationVector.z < 0) {
  48442. this.alpha = 2 * Math.PI - this.alpha;
  48443. }
  48444. // Beta
  48445. this.beta = Math.acos(this._computationVector.y / this.radius);
  48446. this._checkLimits();
  48447. };
  48448. ArcRotateCamera.prototype.setPosition = function (position) {
  48449. if (this.position.equals(position)) {
  48450. return;
  48451. }
  48452. this.position.copyFrom(position);
  48453. this.rebuildAnglesAndRadius();
  48454. };
  48455. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48456. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48457. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48458. if (target.getBoundingInfo) {
  48459. if (toBoundingCenter) {
  48460. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48461. }
  48462. else {
  48463. this._targetBoundingCenter = null;
  48464. }
  48465. this._targetHost = target;
  48466. this._target = this._getTargetPosition();
  48467. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48468. }
  48469. else {
  48470. var newTarget = target;
  48471. var currentTarget = this._getTargetPosition();
  48472. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48473. return;
  48474. }
  48475. this._targetHost = null;
  48476. this._target = newTarget;
  48477. this._targetBoundingCenter = null;
  48478. this.onMeshTargetChangedObservable.notifyObservers(null);
  48479. }
  48480. this.rebuildAnglesAndRadius();
  48481. };
  48482. /** @hidden */
  48483. ArcRotateCamera.prototype._getViewMatrix = function () {
  48484. // Compute
  48485. var cosa = Math.cos(this.alpha);
  48486. var sina = Math.sin(this.alpha);
  48487. var cosb = Math.cos(this.beta);
  48488. var sinb = Math.sin(this.beta);
  48489. if (sinb === 0) {
  48490. sinb = 0.0001;
  48491. }
  48492. var target = this._getTargetPosition();
  48493. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48494. target.addToRef(this._computationVector, this._newPosition);
  48495. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48496. if (!this._collider) {
  48497. this._collider = new BABYLON.Collider();
  48498. }
  48499. this._collider._radius = this.collisionRadius;
  48500. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48501. this._collisionTriggered = true;
  48502. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48503. }
  48504. else {
  48505. this.position.copyFrom(this._newPosition);
  48506. var up = this.upVector;
  48507. if (this.allowUpsideDown && sinb < 0) {
  48508. up = up.clone();
  48509. up = up.negate();
  48510. }
  48511. this._computeViewMatrix(this.position, target, up);
  48512. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48513. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48514. }
  48515. this._currentTarget = target;
  48516. return this._viewMatrix;
  48517. };
  48518. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48519. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48520. meshes = meshes || this.getScene().meshes;
  48521. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48522. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48523. this.radius = distance * this.zoomOnFactor;
  48524. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48525. };
  48526. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48527. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48528. var meshesOrMinMaxVector;
  48529. var distance;
  48530. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48531. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48532. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48533. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48534. }
  48535. else { //minMaxVector and distance
  48536. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48537. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48538. distance = minMaxVectorAndDistance.distance;
  48539. }
  48540. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48541. if (!doNotUpdateMaxZ) {
  48542. this.maxZ = distance * 2;
  48543. }
  48544. };
  48545. /**
  48546. * @override
  48547. * Override Camera.createRigCamera
  48548. */
  48549. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48550. var alphaShift = 0;
  48551. switch (this.cameraRigMode) {
  48552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48553. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48554. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48555. case BABYLON.Camera.RIG_MODE_VR:
  48556. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48557. break;
  48558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48559. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48560. break;
  48561. }
  48562. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48563. rigCam._cameraRigParams = {};
  48564. return rigCam;
  48565. };
  48566. /**
  48567. * @hidden
  48568. * @override
  48569. * Override Camera._updateRigCameras
  48570. */
  48571. ArcRotateCamera.prototype._updateRigCameras = function () {
  48572. var camLeft = this._rigCameras[0];
  48573. var camRight = this._rigCameras[1];
  48574. camLeft.beta = camRight.beta = this.beta;
  48575. camLeft.radius = camRight.radius = this.radius;
  48576. switch (this.cameraRigMode) {
  48577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48578. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48579. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48580. case BABYLON.Camera.RIG_MODE_VR:
  48581. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48582. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48583. break;
  48584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48585. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48586. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48587. break;
  48588. }
  48589. _super.prototype._updateRigCameras.call(this);
  48590. };
  48591. ArcRotateCamera.prototype.dispose = function () {
  48592. this.inputs.clear();
  48593. _super.prototype.dispose.call(this);
  48594. };
  48595. ArcRotateCamera.prototype.getClassName = function () {
  48596. return "ArcRotateCamera";
  48597. };
  48598. __decorate([
  48599. BABYLON.serialize()
  48600. ], ArcRotateCamera.prototype, "alpha", void 0);
  48601. __decorate([
  48602. BABYLON.serialize()
  48603. ], ArcRotateCamera.prototype, "beta", void 0);
  48604. __decorate([
  48605. BABYLON.serialize()
  48606. ], ArcRotateCamera.prototype, "radius", void 0);
  48607. __decorate([
  48608. BABYLON.serializeAsVector3("target")
  48609. ], ArcRotateCamera.prototype, "_target", void 0);
  48610. __decorate([
  48611. BABYLON.serialize()
  48612. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48613. __decorate([
  48614. BABYLON.serialize()
  48615. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48616. __decorate([
  48617. BABYLON.serialize()
  48618. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48619. __decorate([
  48620. BABYLON.serialize()
  48621. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48622. __decorate([
  48623. BABYLON.serialize()
  48624. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48625. __decorate([
  48626. BABYLON.serialize()
  48627. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48628. __decorate([
  48629. BABYLON.serialize()
  48630. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48631. __decorate([
  48632. BABYLON.serialize()
  48633. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48634. __decorate([
  48635. BABYLON.serialize()
  48636. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48637. __decorate([
  48638. BABYLON.serialize()
  48639. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48640. __decorate([
  48641. BABYLON.serialize()
  48642. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48643. __decorate([
  48644. BABYLON.serialize()
  48645. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48646. __decorate([
  48647. BABYLON.serialize()
  48648. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48649. __decorate([
  48650. BABYLON.serializeAsVector3()
  48651. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48652. __decorate([
  48653. BABYLON.serialize()
  48654. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48655. __decorate([
  48656. BABYLON.serialize()
  48657. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48658. __decorate([
  48659. BABYLON.serialize()
  48660. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48661. return ArcRotateCamera;
  48662. }(BABYLON.TargetCamera));
  48663. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48664. })(BABYLON || (BABYLON = {}));
  48665. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48666. var BABYLON;
  48667. (function (BABYLON) {
  48668. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48669. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48670. });
  48671. /**
  48672. * The HemisphericLight simulates the ambient environment light,
  48673. * so the passed direction is the light reflection direction, not the incoming direction.
  48674. */
  48675. var HemisphericLight = /** @class */ (function (_super) {
  48676. __extends(HemisphericLight, _super);
  48677. /**
  48678. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48679. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48680. * The HemisphericLight can't cast shadows.
  48681. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48682. * @param name The friendly name of the light
  48683. * @param direction The direction of the light reflection
  48684. * @param scene The scene the light belongs to
  48685. */
  48686. function HemisphericLight(name, direction, scene) {
  48687. var _this = _super.call(this, name, scene) || this;
  48688. /**
  48689. * The groundColor is the light in the opposite direction to the one specified during creation.
  48690. * 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.
  48691. */
  48692. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48693. _this.direction = direction || BABYLON.Vector3.Up();
  48694. return _this;
  48695. }
  48696. HemisphericLight.prototype._buildUniformLayout = function () {
  48697. this._uniformBuffer.addUniform("vLightData", 4);
  48698. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48699. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48700. this._uniformBuffer.addUniform("vLightGround", 3);
  48701. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48702. this._uniformBuffer.addUniform("depthValues", 2);
  48703. this._uniformBuffer.create();
  48704. };
  48705. /**
  48706. * Returns the string "HemisphericLight".
  48707. * @return The class name
  48708. */
  48709. HemisphericLight.prototype.getClassName = function () {
  48710. return "HemisphericLight";
  48711. };
  48712. /**
  48713. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48714. * Returns the updated direction.
  48715. * @param target The target the direction should point to
  48716. * @return The computed direction
  48717. */
  48718. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48719. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48720. return this.direction;
  48721. };
  48722. /**
  48723. * Returns the shadow generator associated to the light.
  48724. * @returns Always null for hemispheric lights because it does not support shadows.
  48725. */
  48726. HemisphericLight.prototype.getShadowGenerator = function () {
  48727. return null;
  48728. };
  48729. /**
  48730. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48731. * @param effect The effect to update
  48732. * @param lightIndex The index of the light in the effect to update
  48733. * @returns The hemispheric light
  48734. */
  48735. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48736. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48737. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48738. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48739. return this;
  48740. };
  48741. /**
  48742. * @hidden internal use only.
  48743. */
  48744. HemisphericLight.prototype._getWorldMatrix = function () {
  48745. if (!this._worldMatrix) {
  48746. this._worldMatrix = BABYLON.Matrix.Identity();
  48747. }
  48748. return this._worldMatrix;
  48749. };
  48750. /**
  48751. * Returns the integer 3.
  48752. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48753. */
  48754. HemisphericLight.prototype.getTypeID = function () {
  48755. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48756. };
  48757. /**
  48758. * Prepares the list of defines specific to the light type.
  48759. * @param defines the list of defines
  48760. * @param lightIndex defines the index of the light for the effect
  48761. */
  48762. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48763. defines["HEMILIGHT" + lightIndex] = true;
  48764. };
  48765. __decorate([
  48766. BABYLON.serializeAsColor3()
  48767. ], HemisphericLight.prototype, "groundColor", void 0);
  48768. __decorate([
  48769. BABYLON.serializeAsVector3()
  48770. ], HemisphericLight.prototype, "direction", void 0);
  48771. return HemisphericLight;
  48772. }(BABYLON.Light));
  48773. BABYLON.HemisphericLight = HemisphericLight;
  48774. })(BABYLON || (BABYLON = {}));
  48775. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48776. var BABYLON;
  48777. (function (BABYLON) {
  48778. /**
  48779. * Base implementation IShadowLight
  48780. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48781. */
  48782. var ShadowLight = /** @class */ (function (_super) {
  48783. __extends(ShadowLight, _super);
  48784. function ShadowLight() {
  48785. var _this = _super !== null && _super.apply(this, arguments) || this;
  48786. _this._needProjectionMatrixCompute = true;
  48787. return _this;
  48788. }
  48789. ShadowLight.prototype._setPosition = function (value) {
  48790. this._position = value;
  48791. };
  48792. Object.defineProperty(ShadowLight.prototype, "position", {
  48793. /**
  48794. * Sets the position the shadow will be casted from. Also use as the light position for both
  48795. * point and spot lights.
  48796. */
  48797. get: function () {
  48798. return this._position;
  48799. },
  48800. /**
  48801. * Sets the position the shadow will be casted from. Also use as the light position for both
  48802. * point and spot lights.
  48803. */
  48804. set: function (value) {
  48805. this._setPosition(value);
  48806. },
  48807. enumerable: true,
  48808. configurable: true
  48809. });
  48810. ShadowLight.prototype._setDirection = function (value) {
  48811. this._direction = value;
  48812. };
  48813. Object.defineProperty(ShadowLight.prototype, "direction", {
  48814. /**
  48815. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48816. * Also use as the light direction on spot and directional lights.
  48817. */
  48818. get: function () {
  48819. return this._direction;
  48820. },
  48821. /**
  48822. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48823. * Also use as the light direction on spot and directional lights.
  48824. */
  48825. set: function (value) {
  48826. this._setDirection(value);
  48827. },
  48828. enumerable: true,
  48829. configurable: true
  48830. });
  48831. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48832. /**
  48833. * Gets the shadow projection clipping minimum z value.
  48834. */
  48835. get: function () {
  48836. return this._shadowMinZ;
  48837. },
  48838. /**
  48839. * Sets the shadow projection clipping minimum z value.
  48840. */
  48841. set: function (value) {
  48842. this._shadowMinZ = value;
  48843. this.forceProjectionMatrixCompute();
  48844. },
  48845. enumerable: true,
  48846. configurable: true
  48847. });
  48848. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48849. /**
  48850. * Sets the shadow projection clipping maximum z value.
  48851. */
  48852. get: function () {
  48853. return this._shadowMaxZ;
  48854. },
  48855. /**
  48856. * Gets the shadow projection clipping maximum z value.
  48857. */
  48858. set: function (value) {
  48859. this._shadowMaxZ = value;
  48860. this.forceProjectionMatrixCompute();
  48861. },
  48862. enumerable: true,
  48863. configurable: true
  48864. });
  48865. /**
  48866. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48867. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48868. */
  48869. ShadowLight.prototype.computeTransformedInformation = function () {
  48870. if (this.parent && this.parent.getWorldMatrix) {
  48871. if (!this.transformedPosition) {
  48872. this.transformedPosition = BABYLON.Vector3.Zero();
  48873. }
  48874. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48875. // In case the direction is present.
  48876. if (this.direction) {
  48877. if (!this.transformedDirection) {
  48878. this.transformedDirection = BABYLON.Vector3.Zero();
  48879. }
  48880. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48881. }
  48882. return true;
  48883. }
  48884. return false;
  48885. };
  48886. /**
  48887. * Return the depth scale used for the shadow map.
  48888. * @returns the depth scale.
  48889. */
  48890. ShadowLight.prototype.getDepthScale = function () {
  48891. return 50.0;
  48892. };
  48893. /**
  48894. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48895. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48896. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48897. */
  48898. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48899. return this.transformedDirection ? this.transformedDirection : this.direction;
  48900. };
  48901. /**
  48902. * Returns the ShadowLight absolute position in the World.
  48903. * @returns the position vector in world space
  48904. */
  48905. ShadowLight.prototype.getAbsolutePosition = function () {
  48906. return this.transformedPosition ? this.transformedPosition : this.position;
  48907. };
  48908. /**
  48909. * Sets the ShadowLight direction toward the passed target.
  48910. * @param target The point tot target in local space
  48911. * @returns the updated ShadowLight direction
  48912. */
  48913. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48914. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48915. return this.direction;
  48916. };
  48917. /**
  48918. * Returns the light rotation in euler definition.
  48919. * @returns the x y z rotation in local space.
  48920. */
  48921. ShadowLight.prototype.getRotation = function () {
  48922. this.direction.normalize();
  48923. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48924. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48925. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48926. };
  48927. /**
  48928. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48929. * @returns true if a cube texture needs to be use
  48930. */
  48931. ShadowLight.prototype.needCube = function () {
  48932. return false;
  48933. };
  48934. /**
  48935. * Detects if the projection matrix requires to be recomputed this frame.
  48936. * @returns true if it requires to be recomputed otherwise, false.
  48937. */
  48938. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48939. return this._needProjectionMatrixCompute;
  48940. };
  48941. /**
  48942. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48943. */
  48944. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48945. this._needProjectionMatrixCompute = true;
  48946. };
  48947. /**
  48948. * Get the world matrix of the sahdow lights.
  48949. * @hidden Internal Use Only
  48950. */
  48951. ShadowLight.prototype._getWorldMatrix = function () {
  48952. if (!this._worldMatrix) {
  48953. this._worldMatrix = BABYLON.Matrix.Identity();
  48954. }
  48955. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48956. return this._worldMatrix;
  48957. };
  48958. /**
  48959. * Gets the minZ used for shadow according to both the scene and the light.
  48960. * @param activeCamera The camera we are returning the min for
  48961. * @returns the depth min z
  48962. */
  48963. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48964. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48965. };
  48966. /**
  48967. * Gets the maxZ used for shadow according to both the scene and the light.
  48968. * @param activeCamera The camera we are returning the max for
  48969. * @returns the depth max z
  48970. */
  48971. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48972. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48973. };
  48974. /**
  48975. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48976. * @param matrix The materix to updated with the projection information
  48977. * @param viewMatrix The transform matrix of the light
  48978. * @param renderList The list of mesh to render in the map
  48979. * @returns The current light
  48980. */
  48981. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48982. if (this.customProjectionMatrixBuilder) {
  48983. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48984. }
  48985. else {
  48986. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48987. }
  48988. return this;
  48989. };
  48990. __decorate([
  48991. BABYLON.serializeAsVector3()
  48992. ], ShadowLight.prototype, "position", null);
  48993. __decorate([
  48994. BABYLON.serializeAsVector3()
  48995. ], ShadowLight.prototype, "direction", null);
  48996. __decorate([
  48997. BABYLON.serialize()
  48998. ], ShadowLight.prototype, "shadowMinZ", null);
  48999. __decorate([
  49000. BABYLON.serialize()
  49001. ], ShadowLight.prototype, "shadowMaxZ", null);
  49002. return ShadowLight;
  49003. }(BABYLON.Light));
  49004. BABYLON.ShadowLight = ShadowLight;
  49005. })(BABYLON || (BABYLON = {}));
  49006. //# sourceMappingURL=babylon.shadowLight.js.map
  49007. var BABYLON;
  49008. (function (BABYLON) {
  49009. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49010. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49011. });
  49012. /**
  49013. * A point light is a light defined by an unique point in world space.
  49014. * The light is emitted in every direction from this point.
  49015. * A good example of a point light is a standard light bulb.
  49016. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49017. */
  49018. var PointLight = /** @class */ (function (_super) {
  49019. __extends(PointLight, _super);
  49020. /**
  49021. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49022. * A PointLight emits the light in every direction.
  49023. * It can cast shadows.
  49024. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49025. * ```javascript
  49026. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49027. * ```
  49028. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49029. * @param name The light friendly name
  49030. * @param position The position of the point light in the scene
  49031. * @param scene The scene the lights belongs to
  49032. */
  49033. function PointLight(name, position, scene) {
  49034. var _this = _super.call(this, name, scene) || this;
  49035. _this._shadowAngle = Math.PI / 2;
  49036. _this.position = position;
  49037. return _this;
  49038. }
  49039. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49040. /**
  49041. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49042. * This specifies what angle the shadow will use to be created.
  49043. *
  49044. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49045. */
  49046. get: function () {
  49047. return this._shadowAngle;
  49048. },
  49049. /**
  49050. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49051. * This specifies what angle the shadow will use to be created.
  49052. *
  49053. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49054. */
  49055. set: function (value) {
  49056. this._shadowAngle = value;
  49057. this.forceProjectionMatrixCompute();
  49058. },
  49059. enumerable: true,
  49060. configurable: true
  49061. });
  49062. Object.defineProperty(PointLight.prototype, "direction", {
  49063. /**
  49064. * Gets the direction if it has been set.
  49065. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49066. */
  49067. get: function () {
  49068. return this._direction;
  49069. },
  49070. /**
  49071. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49072. */
  49073. set: function (value) {
  49074. var previousNeedCube = this.needCube();
  49075. this._direction = value;
  49076. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49077. this._shadowGenerator.recreateShadowMap();
  49078. }
  49079. },
  49080. enumerable: true,
  49081. configurable: true
  49082. });
  49083. /**
  49084. * Returns the string "PointLight"
  49085. * @returns the class name
  49086. */
  49087. PointLight.prototype.getClassName = function () {
  49088. return "PointLight";
  49089. };
  49090. /**
  49091. * Returns the integer 0.
  49092. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49093. */
  49094. PointLight.prototype.getTypeID = function () {
  49095. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49096. };
  49097. /**
  49098. * Specifies wether or not the shadowmap should be a cube texture.
  49099. * @returns true if the shadowmap needs to be a cube texture.
  49100. */
  49101. PointLight.prototype.needCube = function () {
  49102. return !this.direction;
  49103. };
  49104. /**
  49105. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49106. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49107. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49108. */
  49109. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49110. if (this.direction) {
  49111. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49112. }
  49113. else {
  49114. switch (faceIndex) {
  49115. case 0:
  49116. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49117. case 1:
  49118. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49119. case 2:
  49120. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49121. case 3:
  49122. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49123. case 4:
  49124. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49125. case 5:
  49126. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49127. }
  49128. }
  49129. return BABYLON.Vector3.Zero();
  49130. };
  49131. /**
  49132. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49133. * - fov = PI / 2
  49134. * - aspect ratio : 1.0
  49135. * - z-near and far equal to the active camera minZ and maxZ.
  49136. * Returns the PointLight.
  49137. */
  49138. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49139. var activeCamera = this.getScene().activeCamera;
  49140. if (!activeCamera) {
  49141. return;
  49142. }
  49143. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49144. };
  49145. PointLight.prototype._buildUniformLayout = function () {
  49146. this._uniformBuffer.addUniform("vLightData", 4);
  49147. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49148. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49149. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49150. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49151. this._uniformBuffer.addUniform("depthValues", 2);
  49152. this._uniformBuffer.create();
  49153. };
  49154. /**
  49155. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49156. * @param effect The effect to update
  49157. * @param lightIndex The index of the light in the effect to update
  49158. * @returns The point light
  49159. */
  49160. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49161. if (this.computeTransformedInformation()) {
  49162. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49163. }
  49164. else {
  49165. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49166. }
  49167. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49168. return this;
  49169. };
  49170. /**
  49171. * Prepares the list of defines specific to the light type.
  49172. * @param defines the list of defines
  49173. * @param lightIndex defines the index of the light for the effect
  49174. */
  49175. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49176. defines["POINTLIGHT" + lightIndex] = true;
  49177. };
  49178. __decorate([
  49179. BABYLON.serialize()
  49180. ], PointLight.prototype, "shadowAngle", null);
  49181. return PointLight;
  49182. }(BABYLON.ShadowLight));
  49183. BABYLON.PointLight = PointLight;
  49184. })(BABYLON || (BABYLON = {}));
  49185. //# sourceMappingURL=babylon.pointLight.js.map
  49186. var BABYLON;
  49187. (function (BABYLON) {
  49188. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49189. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49190. });
  49191. /**
  49192. * A directional light is defined by a direction (what a surprise!).
  49193. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49194. * 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.
  49195. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49196. */
  49197. var DirectionalLight = /** @class */ (function (_super) {
  49198. __extends(DirectionalLight, _super);
  49199. /**
  49200. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49201. * The directional light is emitted from everywhere in the given direction.
  49202. * It can cast shawdows.
  49203. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49204. * @param name The friendly name of the light
  49205. * @param direction The direction of the light
  49206. * @param scene The scene the light belongs to
  49207. */
  49208. function DirectionalLight(name, direction, scene) {
  49209. var _this = _super.call(this, name, scene) || this;
  49210. _this._shadowFrustumSize = 0;
  49211. _this._shadowOrthoScale = 0.1;
  49212. /**
  49213. * Automatically compute the projection matrix to best fit (including all the casters)
  49214. * on each frame.
  49215. */
  49216. _this.autoUpdateExtends = true;
  49217. // Cache
  49218. _this._orthoLeft = Number.MAX_VALUE;
  49219. _this._orthoRight = Number.MIN_VALUE;
  49220. _this._orthoTop = Number.MIN_VALUE;
  49221. _this._orthoBottom = Number.MAX_VALUE;
  49222. _this.position = direction.scale(-1.0);
  49223. _this.direction = direction;
  49224. return _this;
  49225. }
  49226. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49227. /**
  49228. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49229. */
  49230. get: function () {
  49231. return this._shadowFrustumSize;
  49232. },
  49233. /**
  49234. * Specifies a fix frustum size for the shadow generation.
  49235. */
  49236. set: function (value) {
  49237. this._shadowFrustumSize = value;
  49238. this.forceProjectionMatrixCompute();
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49244. /**
  49245. * Gets the shadow projection scale against the optimal computed one.
  49246. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49247. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49248. */
  49249. get: function () {
  49250. return this._shadowOrthoScale;
  49251. },
  49252. /**
  49253. * Sets the shadow projection scale against the optimal computed one.
  49254. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49255. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49256. */
  49257. set: function (value) {
  49258. this._shadowOrthoScale = value;
  49259. this.forceProjectionMatrixCompute();
  49260. },
  49261. enumerable: true,
  49262. configurable: true
  49263. });
  49264. /**
  49265. * Returns the string "DirectionalLight".
  49266. * @return The class name
  49267. */
  49268. DirectionalLight.prototype.getClassName = function () {
  49269. return "DirectionalLight";
  49270. };
  49271. /**
  49272. * Returns the integer 1.
  49273. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49274. */
  49275. DirectionalLight.prototype.getTypeID = function () {
  49276. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49277. };
  49278. /**
  49279. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49280. * Returns the DirectionalLight Shadow projection matrix.
  49281. */
  49282. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49283. if (this.shadowFrustumSize > 0) {
  49284. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49285. }
  49286. else {
  49287. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49288. }
  49289. };
  49290. /**
  49291. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49292. * Returns the DirectionalLight Shadow projection matrix.
  49293. */
  49294. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49295. var activeCamera = this.getScene().activeCamera;
  49296. if (!activeCamera) {
  49297. return;
  49298. }
  49299. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49300. };
  49301. /**
  49302. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49303. * Returns the DirectionalLight Shadow projection matrix.
  49304. */
  49305. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49306. var activeCamera = this.getScene().activeCamera;
  49307. if (!activeCamera) {
  49308. return;
  49309. }
  49310. // Check extends
  49311. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49312. var tempVector3 = BABYLON.Vector3.Zero();
  49313. this._orthoLeft = Number.MAX_VALUE;
  49314. this._orthoRight = Number.MIN_VALUE;
  49315. this._orthoTop = Number.MIN_VALUE;
  49316. this._orthoBottom = Number.MAX_VALUE;
  49317. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49318. var mesh = renderList[meshIndex];
  49319. if (!mesh) {
  49320. continue;
  49321. }
  49322. var boundingInfo = mesh.getBoundingInfo();
  49323. var boundingBox = boundingInfo.boundingBox;
  49324. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49325. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49326. if (tempVector3.x < this._orthoLeft)
  49327. this._orthoLeft = tempVector3.x;
  49328. if (tempVector3.y < this._orthoBottom)
  49329. this._orthoBottom = tempVector3.y;
  49330. if (tempVector3.x > this._orthoRight)
  49331. this._orthoRight = tempVector3.x;
  49332. if (tempVector3.y > this._orthoTop)
  49333. this._orthoTop = tempVector3.y;
  49334. }
  49335. }
  49336. }
  49337. var xOffset = this._orthoRight - this._orthoLeft;
  49338. var yOffset = this._orthoTop - this._orthoBottom;
  49339. 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);
  49340. };
  49341. DirectionalLight.prototype._buildUniformLayout = function () {
  49342. this._uniformBuffer.addUniform("vLightData", 4);
  49343. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49344. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49345. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49346. this._uniformBuffer.addUniform("depthValues", 2);
  49347. this._uniformBuffer.create();
  49348. };
  49349. /**
  49350. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49351. * @param effect The effect to update
  49352. * @param lightIndex The index of the light in the effect to update
  49353. * @returns The directional light
  49354. */
  49355. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49356. if (this.computeTransformedInformation()) {
  49357. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49358. return this;
  49359. }
  49360. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49361. return this;
  49362. };
  49363. /**
  49364. * Gets the minZ used for shadow according to both the scene and the light.
  49365. *
  49366. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49367. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49368. * @param activeCamera The camera we are returning the min for
  49369. * @returns the depth min z
  49370. */
  49371. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49372. return 1;
  49373. };
  49374. /**
  49375. * Gets the maxZ used for shadow according to both the scene and the light.
  49376. *
  49377. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49378. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49379. * @param activeCamera The camera we are returning the max for
  49380. * @returns the depth max z
  49381. */
  49382. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49383. return 1;
  49384. };
  49385. /**
  49386. * Prepares the list of defines specific to the light type.
  49387. * @param defines the list of defines
  49388. * @param lightIndex defines the index of the light for the effect
  49389. */
  49390. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49391. defines["DIRLIGHT" + lightIndex] = true;
  49392. };
  49393. __decorate([
  49394. BABYLON.serialize()
  49395. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49396. __decorate([
  49397. BABYLON.serialize()
  49398. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49399. __decorate([
  49400. BABYLON.serialize()
  49401. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49402. return DirectionalLight;
  49403. }(BABYLON.ShadowLight));
  49404. BABYLON.DirectionalLight = DirectionalLight;
  49405. })(BABYLON || (BABYLON = {}));
  49406. //# sourceMappingURL=babylon.directionalLight.js.map
  49407. var BABYLON;
  49408. (function (BABYLON) {
  49409. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49410. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49411. });
  49412. /**
  49413. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49414. * These values define a cone of light starting from the position, emitting toward the direction.
  49415. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49416. * and the exponent defines the speed of the decay of the light with distance (reach).
  49417. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49418. */
  49419. var SpotLight = /** @class */ (function (_super) {
  49420. __extends(SpotLight, _super);
  49421. /**
  49422. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49423. * It can cast shadows.
  49424. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49425. * @param name The light friendly name
  49426. * @param position The position of the spot light in the scene
  49427. * @param direction The direction of the light in the scene
  49428. * @param angle The cone angle of the light in Radians
  49429. * @param exponent The light decay speed with the distance from the emission spot
  49430. * @param scene The scene the lights belongs to
  49431. */
  49432. function SpotLight(name, position, direction, angle, exponent, scene) {
  49433. var _this = _super.call(this, name, scene) || this;
  49434. _this._innerAngle = 0;
  49435. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49436. _this._projectionTextureLightNear = 1e-6;
  49437. _this._projectionTextureLightFar = 1000.0;
  49438. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49439. _this._projectionTextureViewLightDirty = true;
  49440. _this._projectionTextureProjectionLightDirty = true;
  49441. _this._projectionTextureDirty = true;
  49442. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49443. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49444. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49445. _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);
  49446. _this.position = position;
  49447. _this.direction = direction;
  49448. _this.angle = angle;
  49449. _this.exponent = exponent;
  49450. return _this;
  49451. }
  49452. Object.defineProperty(SpotLight.prototype, "angle", {
  49453. /**
  49454. * Gets the cone angle of the spot light in Radians.
  49455. */
  49456. get: function () {
  49457. return this._angle;
  49458. },
  49459. /**
  49460. * Sets the cone angle of the spot light in Radians.
  49461. */
  49462. set: function (value) {
  49463. this._angle = value;
  49464. this._cosHalfAngle = Math.cos(value * 0.5);
  49465. this._projectionTextureProjectionLightDirty = true;
  49466. this.forceProjectionMatrixCompute();
  49467. this._computeAngleValues();
  49468. },
  49469. enumerable: true,
  49470. configurable: true
  49471. });
  49472. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49473. /**
  49474. * Only used in gltf falloff mode, this defines the angle where
  49475. * the directional falloff will start before cutting at angle which could be seen
  49476. * as outer angle.
  49477. */
  49478. get: function () {
  49479. return this._angle;
  49480. },
  49481. /**
  49482. * Only used in gltf falloff mode, this defines the angle where
  49483. * the directional falloff will start before cutting at angle which could be seen
  49484. * as outer angle.
  49485. */
  49486. set: function (value) {
  49487. this._innerAngle = value;
  49488. this._computeAngleValues();
  49489. },
  49490. enumerable: true,
  49491. configurable: true
  49492. });
  49493. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49494. /**
  49495. * Allows scaling the angle of the light for shadow generation only.
  49496. */
  49497. get: function () {
  49498. return this._shadowAngleScale;
  49499. },
  49500. /**
  49501. * Allows scaling the angle of the light for shadow generation only.
  49502. */
  49503. set: function (value) {
  49504. this._shadowAngleScale = value;
  49505. this.forceProjectionMatrixCompute();
  49506. },
  49507. enumerable: true,
  49508. configurable: true
  49509. });
  49510. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49511. /**
  49512. * Allows reading the projecton texture
  49513. */
  49514. get: function () {
  49515. return this._projectionTextureMatrix;
  49516. },
  49517. enumerable: true,
  49518. configurable: true
  49519. });
  49520. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49521. /**
  49522. * Gets the near clip of the Spotlight for texture projection.
  49523. */
  49524. get: function () {
  49525. return this._projectionTextureLightNear;
  49526. },
  49527. /**
  49528. * Sets the near clip of the Spotlight for texture projection.
  49529. */
  49530. set: function (value) {
  49531. this._projectionTextureLightNear = value;
  49532. this._projectionTextureProjectionLightDirty = true;
  49533. },
  49534. enumerable: true,
  49535. configurable: true
  49536. });
  49537. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49538. /**
  49539. * Gets the far clip of the Spotlight for texture projection.
  49540. */
  49541. get: function () {
  49542. return this._projectionTextureLightFar;
  49543. },
  49544. /**
  49545. * Sets the far clip of the Spotlight for texture projection.
  49546. */
  49547. set: function (value) {
  49548. this._projectionTextureLightFar = value;
  49549. this._projectionTextureProjectionLightDirty = true;
  49550. },
  49551. enumerable: true,
  49552. configurable: true
  49553. });
  49554. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49555. /**
  49556. * Gets the Up vector of the Spotlight for texture projection.
  49557. */
  49558. get: function () {
  49559. return this._projectionTextureUpDirection;
  49560. },
  49561. /**
  49562. * Sets the Up vector of the Spotlight for texture projection.
  49563. */
  49564. set: function (value) {
  49565. this._projectionTextureUpDirection = value;
  49566. this._projectionTextureProjectionLightDirty = true;
  49567. },
  49568. enumerable: true,
  49569. configurable: true
  49570. });
  49571. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49572. /**
  49573. * Gets the projection texture of the light.
  49574. */
  49575. get: function () {
  49576. return this._projectionTexture;
  49577. },
  49578. /**
  49579. * Sets the projection texture of the light.
  49580. */
  49581. set: function (value) {
  49582. this._projectionTexture = value;
  49583. this._projectionTextureDirty = true;
  49584. },
  49585. enumerable: true,
  49586. configurable: true
  49587. });
  49588. /**
  49589. * Returns the string "SpotLight".
  49590. * @returns the class name
  49591. */
  49592. SpotLight.prototype.getClassName = function () {
  49593. return "SpotLight";
  49594. };
  49595. /**
  49596. * Returns the integer 2.
  49597. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49598. */
  49599. SpotLight.prototype.getTypeID = function () {
  49600. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49601. };
  49602. /**
  49603. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49604. */
  49605. SpotLight.prototype._setDirection = function (value) {
  49606. _super.prototype._setDirection.call(this, value);
  49607. this._projectionTextureViewLightDirty = true;
  49608. };
  49609. /**
  49610. * Overrides the position setter to recompute the projection texture view light Matrix.
  49611. */
  49612. SpotLight.prototype._setPosition = function (value) {
  49613. _super.prototype._setPosition.call(this, value);
  49614. this._projectionTextureViewLightDirty = true;
  49615. };
  49616. /**
  49617. * 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.
  49618. * Returns the SpotLight.
  49619. */
  49620. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49621. var activeCamera = this.getScene().activeCamera;
  49622. if (!activeCamera) {
  49623. return;
  49624. }
  49625. this._shadowAngleScale = this._shadowAngleScale || 1;
  49626. var angle = this._shadowAngleScale * this._angle;
  49627. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49628. };
  49629. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49630. this._projectionTextureViewLightDirty = false;
  49631. this._projectionTextureDirty = true;
  49632. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49633. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49634. };
  49635. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49636. this._projectionTextureProjectionLightDirty = false;
  49637. this._projectionTextureDirty = true;
  49638. var light_far = this.projectionTextureLightFar;
  49639. var light_near = this.projectionTextureLightNear;
  49640. var P = light_far / (light_far - light_near);
  49641. var Q = -P * light_near;
  49642. var S = 1.0 / Math.tan(this._angle / 2.0);
  49643. var A = 1.0;
  49644. 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);
  49645. };
  49646. /**
  49647. * Main function for light texture projection matrix computing.
  49648. */
  49649. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49650. this._projectionTextureDirty = false;
  49651. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49652. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49653. };
  49654. SpotLight.prototype._buildUniformLayout = function () {
  49655. this._uniformBuffer.addUniform("vLightData", 4);
  49656. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49657. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49658. this._uniformBuffer.addUniform("vLightDirection", 3);
  49659. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49660. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49661. this._uniformBuffer.addUniform("depthValues", 2);
  49662. this._uniformBuffer.create();
  49663. };
  49664. SpotLight.prototype._computeAngleValues = function () {
  49665. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49666. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49667. };
  49668. /**
  49669. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49670. * @param effect The effect to update
  49671. * @param lightIndex The index of the light in the effect to update
  49672. * @returns The spot light
  49673. */
  49674. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49675. var normalizeDirection;
  49676. if (this.computeTransformedInformation()) {
  49677. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49678. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49679. }
  49680. else {
  49681. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49682. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49683. }
  49684. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49685. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49686. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49687. if (this._projectionTextureViewLightDirty) {
  49688. this._computeProjectionTextureViewLightMatrix();
  49689. }
  49690. if (this._projectionTextureProjectionLightDirty) {
  49691. this._computeProjectionTextureProjectionLightMatrix();
  49692. }
  49693. if (this._projectionTextureDirty) {
  49694. this._computeProjectionTextureMatrix();
  49695. }
  49696. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49697. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49698. }
  49699. return this;
  49700. };
  49701. /**
  49702. * Disposes the light and the associated resources.
  49703. */
  49704. SpotLight.prototype.dispose = function () {
  49705. _super.prototype.dispose.call(this);
  49706. if (this._projectionTexture) {
  49707. this._projectionTexture.dispose();
  49708. }
  49709. };
  49710. /**
  49711. * Prepares the list of defines specific to the light type.
  49712. * @param defines the list of defines
  49713. * @param lightIndex defines the index of the light for the effect
  49714. */
  49715. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49716. defines["SPOTLIGHT" + lightIndex] = true;
  49717. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49718. };
  49719. __decorate([
  49720. BABYLON.serialize()
  49721. ], SpotLight.prototype, "angle", null);
  49722. __decorate([
  49723. BABYLON.serialize()
  49724. ], SpotLight.prototype, "innerAngle", null);
  49725. __decorate([
  49726. BABYLON.serialize()
  49727. ], SpotLight.prototype, "shadowAngleScale", null);
  49728. __decorate([
  49729. BABYLON.serialize()
  49730. ], SpotLight.prototype, "exponent", void 0);
  49731. __decorate([
  49732. BABYLON.serialize()
  49733. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49734. __decorate([
  49735. BABYLON.serialize()
  49736. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49737. __decorate([
  49738. BABYLON.serialize()
  49739. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49740. __decorate([
  49741. BABYLON.serializeAsTexture("projectedLightTexture")
  49742. ], SpotLight.prototype, "_projectionTexture", void 0);
  49743. return SpotLight;
  49744. }(BABYLON.ShadowLight));
  49745. BABYLON.SpotLight = SpotLight;
  49746. })(BABYLON || (BABYLON = {}));
  49747. //# sourceMappingURL=babylon.spotLight.js.map
  49748. var BABYLON;
  49749. (function (BABYLON) {
  49750. /**
  49751. * Class used to override all child animations of a given target
  49752. */
  49753. var AnimationPropertiesOverride = /** @class */ (function () {
  49754. function AnimationPropertiesOverride() {
  49755. /**
  49756. * Gets or sets a value indicating if animation blending must be used
  49757. */
  49758. this.enableBlending = false;
  49759. /**
  49760. * Gets or sets the blending speed to use when enableBlending is true
  49761. */
  49762. this.blendingSpeed = 0.01;
  49763. /**
  49764. * Gets or sets the default loop mode to use
  49765. */
  49766. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49767. }
  49768. return AnimationPropertiesOverride;
  49769. }());
  49770. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49771. })(BABYLON || (BABYLON = {}));
  49772. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49773. var BABYLON;
  49774. (function (BABYLON) {
  49775. /**
  49776. * Represents the range of an animation
  49777. */
  49778. var AnimationRange = /** @class */ (function () {
  49779. /**
  49780. * Initializes the range of an animation
  49781. * @param name The name of the animation range
  49782. * @param from The starting frame of the animation
  49783. * @param to The ending frame of the animation
  49784. */
  49785. function AnimationRange(
  49786. /**The name of the animation range**/
  49787. name,
  49788. /**The starting frame of the animation */
  49789. from,
  49790. /**The ending frame of the animation*/
  49791. to) {
  49792. this.name = name;
  49793. this.from = from;
  49794. this.to = to;
  49795. }
  49796. /**
  49797. * Makes a copy of the animation range
  49798. * @returns A copy of the animation range
  49799. */
  49800. AnimationRange.prototype.clone = function () {
  49801. return new AnimationRange(this.name, this.from, this.to);
  49802. };
  49803. return AnimationRange;
  49804. }());
  49805. BABYLON.AnimationRange = AnimationRange;
  49806. /**
  49807. * Composed of a frame, and an action function
  49808. */
  49809. var AnimationEvent = /** @class */ (function () {
  49810. /**
  49811. * Initializes the animation event
  49812. * @param frame The frame for which the event is triggered
  49813. * @param action The event to perform when triggered
  49814. * @param onlyOnce Specifies if the event should be triggered only once
  49815. */
  49816. function AnimationEvent(
  49817. /** The frame for which the event is triggered **/
  49818. frame,
  49819. /** The event to perform when triggered **/
  49820. action,
  49821. /** Specifies if the event should be triggered only once**/
  49822. onlyOnce) {
  49823. this.frame = frame;
  49824. this.action = action;
  49825. this.onlyOnce = onlyOnce;
  49826. /**
  49827. * Specifies if the animation event is done
  49828. */
  49829. this.isDone = false;
  49830. }
  49831. /** @hidden */
  49832. AnimationEvent.prototype._clone = function () {
  49833. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49834. };
  49835. return AnimationEvent;
  49836. }());
  49837. BABYLON.AnimationEvent = AnimationEvent;
  49838. /**
  49839. * A cursor which tracks a point on a path
  49840. */
  49841. var PathCursor = /** @class */ (function () {
  49842. /**
  49843. * Initializes the path cursor
  49844. * @param path The path to track
  49845. */
  49846. function PathCursor(path) {
  49847. this.path = path;
  49848. /**
  49849. * Stores path cursor callbacks for when an onchange event is triggered
  49850. */
  49851. this._onchange = new Array();
  49852. /**
  49853. * The value of the path cursor
  49854. */
  49855. this.value = 0;
  49856. /**
  49857. * The animation array of the path cursor
  49858. */
  49859. this.animations = new Array();
  49860. }
  49861. /**
  49862. * Gets the cursor point on the path
  49863. * @returns A point on the path cursor at the cursor location
  49864. */
  49865. PathCursor.prototype.getPoint = function () {
  49866. var point = this.path.getPointAtLengthPosition(this.value);
  49867. return new BABYLON.Vector3(point.x, 0, point.y);
  49868. };
  49869. /**
  49870. * Moves the cursor ahead by the step amount
  49871. * @param step The amount to move the cursor forward
  49872. * @returns This path cursor
  49873. */
  49874. PathCursor.prototype.moveAhead = function (step) {
  49875. if (step === void 0) { step = 0.002; }
  49876. this.move(step);
  49877. return this;
  49878. };
  49879. /**
  49880. * Moves the cursor behind by the step amount
  49881. * @param step The amount to move the cursor back
  49882. * @returns This path cursor
  49883. */
  49884. PathCursor.prototype.moveBack = function (step) {
  49885. if (step === void 0) { step = 0.002; }
  49886. this.move(-step);
  49887. return this;
  49888. };
  49889. /**
  49890. * Moves the cursor by the step amount
  49891. * If the step amount is greater than one, an exception is thrown
  49892. * @param step The amount to move the cursor
  49893. * @returns This path cursor
  49894. */
  49895. PathCursor.prototype.move = function (step) {
  49896. if (Math.abs(step) > 1) {
  49897. throw "step size should be less than 1.";
  49898. }
  49899. this.value += step;
  49900. this.ensureLimits();
  49901. this.raiseOnChange();
  49902. return this;
  49903. };
  49904. /**
  49905. * Ensures that the value is limited between zero and one
  49906. * @returns This path cursor
  49907. */
  49908. PathCursor.prototype.ensureLimits = function () {
  49909. while (this.value > 1) {
  49910. this.value -= 1;
  49911. }
  49912. while (this.value < 0) {
  49913. this.value += 1;
  49914. }
  49915. return this;
  49916. };
  49917. /**
  49918. * Runs onchange callbacks on change (used by the animation engine)
  49919. * @returns This path cursor
  49920. */
  49921. PathCursor.prototype.raiseOnChange = function () {
  49922. var _this = this;
  49923. this._onchange.forEach(function (f) { return f(_this); });
  49924. return this;
  49925. };
  49926. /**
  49927. * Executes a function on change
  49928. * @param f A path cursor onchange callback
  49929. * @returns This path cursor
  49930. */
  49931. PathCursor.prototype.onchange = function (f) {
  49932. this._onchange.push(f);
  49933. return this;
  49934. };
  49935. return PathCursor;
  49936. }());
  49937. BABYLON.PathCursor = PathCursor;
  49938. /**
  49939. * Enum for the animation key frame interpolation type
  49940. */
  49941. var AnimationKeyInterpolation;
  49942. (function (AnimationKeyInterpolation) {
  49943. /**
  49944. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49945. */
  49946. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49947. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49948. /**
  49949. * Class used to store any kind of animation
  49950. */
  49951. var Animation = /** @class */ (function () {
  49952. /**
  49953. * Initializes the animation
  49954. * @param name Name of the animation
  49955. * @param targetProperty Property to animate
  49956. * @param framePerSecond The frames per second of the animation
  49957. * @param dataType The data type of the animation
  49958. * @param loopMode The loop mode of the animation
  49959. * @param enableBlendings Specifies if blending should be enabled
  49960. */
  49961. function Animation(
  49962. /**Name of the animation */
  49963. name,
  49964. /**Property to animate */
  49965. targetProperty,
  49966. /**The frames per second of the animation */
  49967. framePerSecond,
  49968. /**The data type of the animation */
  49969. dataType,
  49970. /**The loop mode of the animation */
  49971. loopMode,
  49972. /**Specifies if blending should be enabled */
  49973. enableBlending) {
  49974. this.name = name;
  49975. this.targetProperty = targetProperty;
  49976. this.framePerSecond = framePerSecond;
  49977. this.dataType = dataType;
  49978. this.loopMode = loopMode;
  49979. this.enableBlending = enableBlending;
  49980. /**
  49981. * @hidden Internal use only
  49982. */
  49983. this._runtimeAnimations = new Array();
  49984. /**
  49985. * The set of event that will be linked to this animation
  49986. */
  49987. this._events = new Array();
  49988. /**
  49989. * Stores the blending speed of the animation
  49990. */
  49991. this.blendingSpeed = 0.01;
  49992. /**
  49993. * Stores the animation ranges for the animation
  49994. */
  49995. this._ranges = {};
  49996. this.targetPropertyPath = targetProperty.split(".");
  49997. this.dataType = dataType;
  49998. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49999. }
  50000. /**
  50001. * @hidden Internal use
  50002. */
  50003. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50004. var dataType = undefined;
  50005. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50006. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50007. }
  50008. else if (from instanceof BABYLON.Quaternion) {
  50009. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50010. }
  50011. else if (from instanceof BABYLON.Vector3) {
  50012. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50013. }
  50014. else if (from instanceof BABYLON.Vector2) {
  50015. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50016. }
  50017. else if (from instanceof BABYLON.Color3) {
  50018. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50019. }
  50020. else if (from instanceof BABYLON.Size) {
  50021. dataType = Animation.ANIMATIONTYPE_SIZE;
  50022. }
  50023. if (dataType == undefined) {
  50024. return null;
  50025. }
  50026. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50027. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50028. animation.setKeys(keys);
  50029. if (easingFunction !== undefined) {
  50030. animation.setEasingFunction(easingFunction);
  50031. }
  50032. return animation;
  50033. };
  50034. /**
  50035. * Sets up an animation
  50036. * @param property The property to animate
  50037. * @param animationType The animation type to apply
  50038. * @param framePerSecond The frames per second of the animation
  50039. * @param easingFunction The easing function used in the animation
  50040. * @returns The created animation
  50041. */
  50042. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50043. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50044. animation.setEasingFunction(easingFunction);
  50045. return animation;
  50046. };
  50047. /**
  50048. * Create and start an animation on a node
  50049. * @param name defines the name of the global animation that will be run on all nodes
  50050. * @param node defines the root node where the animation will take place
  50051. * @param targetProperty defines property to animate
  50052. * @param framePerSecond defines the number of frame per second yo use
  50053. * @param totalFrame defines the number of frames in total
  50054. * @param from defines the initial value
  50055. * @param to defines the final value
  50056. * @param loopMode defines which loop mode you want to use (off by default)
  50057. * @param easingFunction defines the easing function to use (linear by default)
  50058. * @param onAnimationEnd defines the callback to call when animation end
  50059. * @returns the animatable created for this animation
  50060. */
  50061. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50062. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50063. if (!animation) {
  50064. return null;
  50065. }
  50066. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50067. };
  50068. /**
  50069. * Create and start an animation on a node and its descendants
  50070. * @param name defines the name of the global animation that will be run on all nodes
  50071. * @param node defines the root node where the animation will take place
  50072. * @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
  50073. * @param targetProperty defines property to animate
  50074. * @param framePerSecond defines the number of frame per second to use
  50075. * @param totalFrame defines the number of frames in total
  50076. * @param from defines the initial value
  50077. * @param to defines the final value
  50078. * @param loopMode defines which loop mode you want to use (off by default)
  50079. * @param easingFunction defines the easing function to use (linear by default)
  50080. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50081. * @returns the list of animatables created for all nodes
  50082. * @example https://www.babylonjs-playground.com/#MH0VLI
  50083. */
  50084. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50085. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50086. if (!animation) {
  50087. return null;
  50088. }
  50089. var scene = node.getScene();
  50090. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50091. };
  50092. /**
  50093. * Creates a new animation, merges it with the existing animations and starts it
  50094. * @param name Name of the animation
  50095. * @param node Node which contains the scene that begins the animations
  50096. * @param targetProperty Specifies which property to animate
  50097. * @param framePerSecond The frames per second of the animation
  50098. * @param totalFrame The total number of frames
  50099. * @param from The frame at the beginning of the animation
  50100. * @param to The frame at the end of the animation
  50101. * @param loopMode Specifies the loop mode of the animation
  50102. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50103. * @param onAnimationEnd Callback to run once the animation is complete
  50104. * @returns Nullable animation
  50105. */
  50106. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50107. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50108. if (!animation) {
  50109. return null;
  50110. }
  50111. node.animations.push(animation);
  50112. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50113. };
  50114. /**
  50115. * Transition property of an host to the target Value
  50116. * @param property The property to transition
  50117. * @param targetValue The target Value of the property
  50118. * @param host The object where the property to animate belongs
  50119. * @param scene Scene used to run the animation
  50120. * @param frameRate Framerate (in frame/s) to use
  50121. * @param transition The transition type we want to use
  50122. * @param duration The duration of the animation, in milliseconds
  50123. * @param onAnimationEnd Callback trigger at the end of the animation
  50124. * @returns Nullable animation
  50125. */
  50126. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50127. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50128. if (duration <= 0) {
  50129. host[property] = targetValue;
  50130. if (onAnimationEnd) {
  50131. onAnimationEnd();
  50132. }
  50133. return null;
  50134. }
  50135. var endFrame = frameRate * (duration / 1000);
  50136. transition.setKeys([{
  50137. frame: 0,
  50138. value: host[property].clone ? host[property].clone() : host[property]
  50139. },
  50140. {
  50141. frame: endFrame,
  50142. value: targetValue
  50143. }]);
  50144. if (!host.animations) {
  50145. host.animations = [];
  50146. }
  50147. host.animations.push(transition);
  50148. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50149. animation.onAnimationEnd = onAnimationEnd;
  50150. return animation;
  50151. };
  50152. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50153. /**
  50154. * Return the array of runtime animations currently using this animation
  50155. */
  50156. get: function () {
  50157. return this._runtimeAnimations;
  50158. },
  50159. enumerable: true,
  50160. configurable: true
  50161. });
  50162. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50163. /**
  50164. * Specifies if any of the runtime animations are currently running
  50165. */
  50166. get: function () {
  50167. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50168. var runtimeAnimation = _a[_i];
  50169. if (!runtimeAnimation.isStopped) {
  50170. return true;
  50171. }
  50172. }
  50173. return false;
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. // Methods
  50179. /**
  50180. * Converts the animation to a string
  50181. * @param fullDetails support for multiple levels of logging within scene loading
  50182. * @returns String form of the animation
  50183. */
  50184. Animation.prototype.toString = function (fullDetails) {
  50185. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50186. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50187. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50188. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50189. if (fullDetails) {
  50190. ret += ", Ranges: {";
  50191. var first = true;
  50192. for (var name in this._ranges) {
  50193. if (first) {
  50194. ret += ", ";
  50195. first = false;
  50196. }
  50197. ret += name;
  50198. }
  50199. ret += "}";
  50200. }
  50201. return ret;
  50202. };
  50203. /**
  50204. * Add an event to this animation
  50205. * @param event Event to add
  50206. */
  50207. Animation.prototype.addEvent = function (event) {
  50208. this._events.push(event);
  50209. };
  50210. /**
  50211. * Remove all events found at the given frame
  50212. * @param frame The frame to remove events from
  50213. */
  50214. Animation.prototype.removeEvents = function (frame) {
  50215. for (var index = 0; index < this._events.length; index++) {
  50216. if (this._events[index].frame === frame) {
  50217. this._events.splice(index, 1);
  50218. index--;
  50219. }
  50220. }
  50221. };
  50222. /**
  50223. * Retrieves all the events from the animation
  50224. * @returns Events from the animation
  50225. */
  50226. Animation.prototype.getEvents = function () {
  50227. return this._events;
  50228. };
  50229. /**
  50230. * Creates an animation range
  50231. * @param name Name of the animation range
  50232. * @param from Starting frame of the animation range
  50233. * @param to Ending frame of the animation
  50234. */
  50235. Animation.prototype.createRange = function (name, from, to) {
  50236. // check name not already in use; could happen for bones after serialized
  50237. if (!this._ranges[name]) {
  50238. this._ranges[name] = new AnimationRange(name, from, to);
  50239. }
  50240. };
  50241. /**
  50242. * Deletes an animation range by name
  50243. * @param name Name of the animation range to delete
  50244. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50245. */
  50246. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50247. if (deleteFrames === void 0) { deleteFrames = true; }
  50248. var range = this._ranges[name];
  50249. if (!range) {
  50250. return;
  50251. }
  50252. if (deleteFrames) {
  50253. var from = range.from;
  50254. var to = range.to;
  50255. // this loop MUST go high to low for multiple splices to work
  50256. for (var key = this._keys.length - 1; key >= 0; key--) {
  50257. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50258. this._keys.splice(key, 1);
  50259. }
  50260. }
  50261. }
  50262. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50263. };
  50264. /**
  50265. * Gets the animation range by name, or null if not defined
  50266. * @param name Name of the animation range
  50267. * @returns Nullable animation range
  50268. */
  50269. Animation.prototype.getRange = function (name) {
  50270. return this._ranges[name];
  50271. };
  50272. /**
  50273. * Gets the key frames from the animation
  50274. * @returns The key frames of the animation
  50275. */
  50276. Animation.prototype.getKeys = function () {
  50277. return this._keys;
  50278. };
  50279. /**
  50280. * Gets the highest frame rate of the animation
  50281. * @returns Highest frame rate of the animation
  50282. */
  50283. Animation.prototype.getHighestFrame = function () {
  50284. var ret = 0;
  50285. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50286. if (ret < this._keys[key].frame) {
  50287. ret = this._keys[key].frame;
  50288. }
  50289. }
  50290. return ret;
  50291. };
  50292. /**
  50293. * Gets the easing function of the animation
  50294. * @returns Easing function of the animation
  50295. */
  50296. Animation.prototype.getEasingFunction = function () {
  50297. return this._easingFunction;
  50298. };
  50299. /**
  50300. * Sets the easing function of the animation
  50301. * @param easingFunction A custom mathematical formula for animation
  50302. */
  50303. Animation.prototype.setEasingFunction = function (easingFunction) {
  50304. this._easingFunction = easingFunction;
  50305. };
  50306. /**
  50307. * Interpolates a scalar linearly
  50308. * @param startValue Start value of the animation curve
  50309. * @param endValue End value of the animation curve
  50310. * @param gradient Scalar amount to interpolate
  50311. * @returns Interpolated scalar value
  50312. */
  50313. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50314. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50315. };
  50316. /**
  50317. * Interpolates a scalar cubically
  50318. * @param startValue Start value of the animation curve
  50319. * @param outTangent End tangent of the animation
  50320. * @param endValue End value of the animation curve
  50321. * @param inTangent Start tangent of the animation curve
  50322. * @param gradient Scalar amount to interpolate
  50323. * @returns Interpolated scalar value
  50324. */
  50325. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50326. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50327. };
  50328. /**
  50329. * Interpolates a quaternion using a spherical linear interpolation
  50330. * @param startValue Start value of the animation curve
  50331. * @param endValue End value of the animation curve
  50332. * @param gradient Scalar amount to interpolate
  50333. * @returns Interpolated quaternion value
  50334. */
  50335. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50336. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50337. };
  50338. /**
  50339. * Interpolates a quaternion cubically
  50340. * @param startValue Start value of the animation curve
  50341. * @param outTangent End tangent of the animation curve
  50342. * @param endValue End value of the animation curve
  50343. * @param inTangent Start tangent of the animation curve
  50344. * @param gradient Scalar amount to interpolate
  50345. * @returns Interpolated quaternion value
  50346. */
  50347. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50348. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50349. };
  50350. /**
  50351. * Interpolates a Vector3 linearl
  50352. * @param startValue Start value of the animation curve
  50353. * @param endValue End value of the animation curve
  50354. * @param gradient Scalar amount to interpolate
  50355. * @returns Interpolated scalar value
  50356. */
  50357. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50358. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50359. };
  50360. /**
  50361. * Interpolates a Vector3 cubically
  50362. * @param startValue Start value of the animation curve
  50363. * @param outTangent End tangent of the animation
  50364. * @param endValue End value of the animation curve
  50365. * @param inTangent Start tangent of the animation curve
  50366. * @param gradient Scalar amount to interpolate
  50367. * @returns InterpolatedVector3 value
  50368. */
  50369. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50370. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50371. };
  50372. /**
  50373. * Interpolates a Vector2 linearly
  50374. * @param startValue Start value of the animation curve
  50375. * @param endValue End value of the animation curve
  50376. * @param gradient Scalar amount to interpolate
  50377. * @returns Interpolated Vector2 value
  50378. */
  50379. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50380. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50381. };
  50382. /**
  50383. * Interpolates a Vector2 cubically
  50384. * @param startValue Start value of the animation curve
  50385. * @param outTangent End tangent of the animation
  50386. * @param endValue End value of the animation curve
  50387. * @param inTangent Start tangent of the animation curve
  50388. * @param gradient Scalar amount to interpolate
  50389. * @returns Interpolated Vector2 value
  50390. */
  50391. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50392. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50393. };
  50394. /**
  50395. * Interpolates a size linearly
  50396. * @param startValue Start value of the animation curve
  50397. * @param endValue End value of the animation curve
  50398. * @param gradient Scalar amount to interpolate
  50399. * @returns Interpolated Size value
  50400. */
  50401. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50402. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50403. };
  50404. /**
  50405. * Interpolates a Color3 linearly
  50406. * @param startValue Start value of the animation curve
  50407. * @param endValue End value of the animation curve
  50408. * @param gradient Scalar amount to interpolate
  50409. * @returns Interpolated Color3 value
  50410. */
  50411. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50412. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50413. };
  50414. /**
  50415. * @hidden Internal use only
  50416. */
  50417. Animation.prototype._getKeyValue = function (value) {
  50418. if (typeof value === "function") {
  50419. return value();
  50420. }
  50421. return value;
  50422. };
  50423. /**
  50424. * @hidden Internal use only
  50425. */
  50426. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50427. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50428. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50429. }
  50430. var keys = this.getKeys();
  50431. // Try to get a hash to find the right key
  50432. 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));
  50433. if (keys[startKeyIndex].frame >= currentFrame) {
  50434. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50435. startKeyIndex--;
  50436. }
  50437. }
  50438. for (var key = startKeyIndex; key < keys.length; key++) {
  50439. var endKey = keys[key + 1];
  50440. if (endKey.frame >= currentFrame) {
  50441. var startKey = keys[key];
  50442. var startValue = this._getKeyValue(startKey.value);
  50443. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50444. return startValue;
  50445. }
  50446. var endValue = this._getKeyValue(endKey.value);
  50447. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50448. var frameDelta = endKey.frame - startKey.frame;
  50449. // gradient : percent of currentFrame between the frame inf and the frame sup
  50450. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50451. // check for easingFunction and correction of gradient
  50452. var easingFunction = this.getEasingFunction();
  50453. if (easingFunction != null) {
  50454. gradient = easingFunction.ease(gradient);
  50455. }
  50456. switch (this.dataType) {
  50457. // Float
  50458. case Animation.ANIMATIONTYPE_FLOAT:
  50459. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50460. switch (loopMode) {
  50461. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50462. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50463. return floatValue;
  50464. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50465. return offsetValue * repeatCount + floatValue;
  50466. }
  50467. break;
  50468. // Quaternion
  50469. case Animation.ANIMATIONTYPE_QUATERNION:
  50470. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50471. switch (loopMode) {
  50472. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50473. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50474. return quatValue;
  50475. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50476. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50477. }
  50478. return quatValue;
  50479. // Vector3
  50480. case Animation.ANIMATIONTYPE_VECTOR3:
  50481. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50482. switch (loopMode) {
  50483. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50484. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50485. return vec3Value;
  50486. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50487. return vec3Value.add(offsetValue.scale(repeatCount));
  50488. }
  50489. // Vector2
  50490. case Animation.ANIMATIONTYPE_VECTOR2:
  50491. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50492. switch (loopMode) {
  50493. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50494. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50495. return vec2Value;
  50496. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50497. return vec2Value.add(offsetValue.scale(repeatCount));
  50498. }
  50499. // Size
  50500. case Animation.ANIMATIONTYPE_SIZE:
  50501. switch (loopMode) {
  50502. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50503. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50504. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50505. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50506. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50507. }
  50508. // Color3
  50509. case Animation.ANIMATIONTYPE_COLOR3:
  50510. switch (loopMode) {
  50511. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50512. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50513. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50514. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50515. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50516. }
  50517. // Matrix
  50518. case Animation.ANIMATIONTYPE_MATRIX:
  50519. switch (loopMode) {
  50520. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50521. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50522. if (Animation.AllowMatricesInterpolation) {
  50523. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50524. }
  50525. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50526. return startValue;
  50527. }
  50528. default:
  50529. break;
  50530. }
  50531. break;
  50532. }
  50533. }
  50534. return this._getKeyValue(keys[keys.length - 1].value);
  50535. };
  50536. /**
  50537. * Defines the function to use to interpolate matrices
  50538. * @param startValue defines the start matrix
  50539. * @param endValue defines the end matrix
  50540. * @param gradient defines the gradient between both matrices
  50541. * @param result defines an optional target matrix where to store the interpolation
  50542. * @returns the interpolated matrix
  50543. */
  50544. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50545. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50546. if (result) {
  50547. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50548. return result;
  50549. }
  50550. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50551. }
  50552. if (result) {
  50553. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50554. return result;
  50555. }
  50556. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50557. };
  50558. /**
  50559. * Makes a copy of the animation
  50560. * @returns Cloned animation
  50561. */
  50562. Animation.prototype.clone = function () {
  50563. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50564. clone.enableBlending = this.enableBlending;
  50565. clone.blendingSpeed = this.blendingSpeed;
  50566. if (this._keys) {
  50567. clone.setKeys(this._keys);
  50568. }
  50569. if (this._ranges) {
  50570. clone._ranges = {};
  50571. for (var name in this._ranges) {
  50572. var range = this._ranges[name];
  50573. if (!range) {
  50574. continue;
  50575. }
  50576. clone._ranges[name] = range.clone();
  50577. }
  50578. }
  50579. return clone;
  50580. };
  50581. /**
  50582. * Sets the key frames of the animation
  50583. * @param values The animation key frames to set
  50584. */
  50585. Animation.prototype.setKeys = function (values) {
  50586. this._keys = values.slice(0);
  50587. };
  50588. /**
  50589. * Serializes the animation to an object
  50590. * @returns Serialized object
  50591. */
  50592. Animation.prototype.serialize = function () {
  50593. var serializationObject = {};
  50594. serializationObject.name = this.name;
  50595. serializationObject.property = this.targetProperty;
  50596. serializationObject.framePerSecond = this.framePerSecond;
  50597. serializationObject.dataType = this.dataType;
  50598. serializationObject.loopBehavior = this.loopMode;
  50599. serializationObject.enableBlending = this.enableBlending;
  50600. serializationObject.blendingSpeed = this.blendingSpeed;
  50601. var dataType = this.dataType;
  50602. serializationObject.keys = [];
  50603. var keys = this.getKeys();
  50604. for (var index = 0; index < keys.length; index++) {
  50605. var animationKey = keys[index];
  50606. var key = {};
  50607. key.frame = animationKey.frame;
  50608. switch (dataType) {
  50609. case Animation.ANIMATIONTYPE_FLOAT:
  50610. key.values = [animationKey.value];
  50611. break;
  50612. case Animation.ANIMATIONTYPE_QUATERNION:
  50613. case Animation.ANIMATIONTYPE_MATRIX:
  50614. case Animation.ANIMATIONTYPE_VECTOR3:
  50615. case Animation.ANIMATIONTYPE_COLOR3:
  50616. key.values = animationKey.value.asArray();
  50617. break;
  50618. }
  50619. serializationObject.keys.push(key);
  50620. }
  50621. serializationObject.ranges = [];
  50622. for (var name in this._ranges) {
  50623. var source = this._ranges[name];
  50624. if (!source) {
  50625. continue;
  50626. }
  50627. var range = {};
  50628. range.name = name;
  50629. range.from = source.from;
  50630. range.to = source.to;
  50631. serializationObject.ranges.push(range);
  50632. }
  50633. return serializationObject;
  50634. };
  50635. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50636. /**
  50637. * Get the float animation type
  50638. */
  50639. get: function () {
  50640. return Animation._ANIMATIONTYPE_FLOAT;
  50641. },
  50642. enumerable: true,
  50643. configurable: true
  50644. });
  50645. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50646. /**
  50647. * Get the Vector3 animation type
  50648. */
  50649. get: function () {
  50650. return Animation._ANIMATIONTYPE_VECTOR3;
  50651. },
  50652. enumerable: true,
  50653. configurable: true
  50654. });
  50655. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50656. /**
  50657. * Get the Vector2 animation type
  50658. */
  50659. get: function () {
  50660. return Animation._ANIMATIONTYPE_VECTOR2;
  50661. },
  50662. enumerable: true,
  50663. configurable: true
  50664. });
  50665. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50666. /**
  50667. * Get the Size animation type
  50668. */
  50669. get: function () {
  50670. return Animation._ANIMATIONTYPE_SIZE;
  50671. },
  50672. enumerable: true,
  50673. configurable: true
  50674. });
  50675. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50676. /**
  50677. * Get the Quaternion animation type
  50678. */
  50679. get: function () {
  50680. return Animation._ANIMATIONTYPE_QUATERNION;
  50681. },
  50682. enumerable: true,
  50683. configurable: true
  50684. });
  50685. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50686. /**
  50687. * Get the Matrix animation type
  50688. */
  50689. get: function () {
  50690. return Animation._ANIMATIONTYPE_MATRIX;
  50691. },
  50692. enumerable: true,
  50693. configurable: true
  50694. });
  50695. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50696. /**
  50697. * Get the Color3 animation type
  50698. */
  50699. get: function () {
  50700. return Animation._ANIMATIONTYPE_COLOR3;
  50701. },
  50702. enumerable: true,
  50703. configurable: true
  50704. });
  50705. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50706. /**
  50707. * Get the Relative Loop Mode
  50708. */
  50709. get: function () {
  50710. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50711. },
  50712. enumerable: true,
  50713. configurable: true
  50714. });
  50715. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50716. /**
  50717. * Get the Cycle Loop Mode
  50718. */
  50719. get: function () {
  50720. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50721. },
  50722. enumerable: true,
  50723. configurable: true
  50724. });
  50725. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50726. /**
  50727. * Get the Constant Loop Mode
  50728. */
  50729. get: function () {
  50730. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50731. },
  50732. enumerable: true,
  50733. configurable: true
  50734. });
  50735. /** @hidden */
  50736. Animation._UniversalLerp = function (left, right, amount) {
  50737. var constructor = left.constructor;
  50738. if (constructor.Lerp) { // Lerp supported
  50739. return constructor.Lerp(left, right, amount);
  50740. }
  50741. else if (constructor.Slerp) { // Slerp supported
  50742. return constructor.Slerp(left, right, amount);
  50743. }
  50744. else if (left.toFixed) { // Number
  50745. return left * (1.0 - amount) + amount * right;
  50746. }
  50747. else { // Blending not supported
  50748. return right;
  50749. }
  50750. };
  50751. /**
  50752. * Parses an animation object and creates an animation
  50753. * @param parsedAnimation Parsed animation object
  50754. * @returns Animation object
  50755. */
  50756. Animation.Parse = function (parsedAnimation) {
  50757. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50758. var dataType = parsedAnimation.dataType;
  50759. var keys = [];
  50760. var data;
  50761. var index;
  50762. if (parsedAnimation.enableBlending) {
  50763. animation.enableBlending = parsedAnimation.enableBlending;
  50764. }
  50765. if (parsedAnimation.blendingSpeed) {
  50766. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50767. }
  50768. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50769. var key = parsedAnimation.keys[index];
  50770. var inTangent;
  50771. var outTangent;
  50772. switch (dataType) {
  50773. case Animation.ANIMATIONTYPE_FLOAT:
  50774. data = key.values[0];
  50775. if (key.values.length >= 1) {
  50776. inTangent = key.values[1];
  50777. }
  50778. if (key.values.length >= 2) {
  50779. outTangent = key.values[2];
  50780. }
  50781. break;
  50782. case Animation.ANIMATIONTYPE_QUATERNION:
  50783. data = BABYLON.Quaternion.FromArray(key.values);
  50784. if (key.values.length >= 8) {
  50785. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50786. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50787. inTangent = _inTangent;
  50788. }
  50789. }
  50790. if (key.values.length >= 12) {
  50791. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50792. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50793. outTangent = _outTangent;
  50794. }
  50795. }
  50796. break;
  50797. case Animation.ANIMATIONTYPE_MATRIX:
  50798. data = BABYLON.Matrix.FromArray(key.values);
  50799. break;
  50800. case Animation.ANIMATIONTYPE_COLOR3:
  50801. data = BABYLON.Color3.FromArray(key.values);
  50802. break;
  50803. case Animation.ANIMATIONTYPE_VECTOR3:
  50804. default:
  50805. data = BABYLON.Vector3.FromArray(key.values);
  50806. break;
  50807. }
  50808. var keyData = {};
  50809. keyData.frame = key.frame;
  50810. keyData.value = data;
  50811. if (inTangent != undefined) {
  50812. keyData.inTangent = inTangent;
  50813. }
  50814. if (outTangent != undefined) {
  50815. keyData.outTangent = outTangent;
  50816. }
  50817. keys.push(keyData);
  50818. }
  50819. animation.setKeys(keys);
  50820. if (parsedAnimation.ranges) {
  50821. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50822. data = parsedAnimation.ranges[index];
  50823. animation.createRange(data.name, data.from, data.to);
  50824. }
  50825. }
  50826. return animation;
  50827. };
  50828. /**
  50829. * Appends the serialized animations from the source animations
  50830. * @param source Source containing the animations
  50831. * @param destination Target to store the animations
  50832. */
  50833. Animation.AppendSerializedAnimations = function (source, destination) {
  50834. if (source.animations) {
  50835. destination.animations = [];
  50836. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50837. var animation = source.animations[animationIndex];
  50838. destination.animations.push(animation.serialize());
  50839. }
  50840. }
  50841. };
  50842. /**
  50843. * Use matrix interpolation instead of using direct key value when animating matrices
  50844. */
  50845. Animation.AllowMatricesInterpolation = false;
  50846. /**
  50847. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50848. */
  50849. Animation.AllowMatrixDecomposeForInterpolation = true;
  50850. // Statics
  50851. /**
  50852. * Float animation type
  50853. */
  50854. Animation._ANIMATIONTYPE_FLOAT = 0;
  50855. /**
  50856. * Vector3 animation type
  50857. */
  50858. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50859. /**
  50860. * Quaternion animation type
  50861. */
  50862. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50863. /**
  50864. * Matrix animation type
  50865. */
  50866. Animation._ANIMATIONTYPE_MATRIX = 3;
  50867. /**
  50868. * Color3 animation type
  50869. */
  50870. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50871. /**
  50872. * Vector2 animation type
  50873. */
  50874. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50875. /**
  50876. * Size animation type
  50877. */
  50878. Animation._ANIMATIONTYPE_SIZE = 6;
  50879. /**
  50880. * Relative Loop Mode
  50881. */
  50882. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50883. /**
  50884. * Cycle Loop Mode
  50885. */
  50886. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50887. /**
  50888. * Constant Loop Mode
  50889. */
  50890. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50891. return Animation;
  50892. }());
  50893. BABYLON.Animation = Animation;
  50894. })(BABYLON || (BABYLON = {}));
  50895. //# sourceMappingURL=babylon.animation.js.map
  50896. var BABYLON;
  50897. (function (BABYLON) {
  50898. /**
  50899. * This class defines the direct association between an animation and a target
  50900. */
  50901. var TargetedAnimation = /** @class */ (function () {
  50902. function TargetedAnimation() {
  50903. }
  50904. return TargetedAnimation;
  50905. }());
  50906. BABYLON.TargetedAnimation = TargetedAnimation;
  50907. /**
  50908. * Use this class to create coordinated animations on multiple targets
  50909. */
  50910. var AnimationGroup = /** @class */ (function () {
  50911. function AnimationGroup(name, scene) {
  50912. if (scene === void 0) { scene = null; }
  50913. this.name = name;
  50914. this._targetedAnimations = new Array();
  50915. this._animatables = new Array();
  50916. this._from = Number.MAX_VALUE;
  50917. this._to = -Number.MAX_VALUE;
  50918. this._speedRatio = 1;
  50919. this.onAnimationEndObservable = new BABYLON.Observable();
  50920. /**
  50921. * This observable will notify when all animations have ended.
  50922. */
  50923. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50924. /**
  50925. * This observable will notify when all animations have paused.
  50926. */
  50927. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50928. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50929. this._scene.animationGroups.push(this);
  50930. }
  50931. Object.defineProperty(AnimationGroup.prototype, "from", {
  50932. /**
  50933. * Gets the first frame
  50934. */
  50935. get: function () {
  50936. return this._from;
  50937. },
  50938. enumerable: true,
  50939. configurable: true
  50940. });
  50941. Object.defineProperty(AnimationGroup.prototype, "to", {
  50942. /**
  50943. * Gets the last frame
  50944. */
  50945. get: function () {
  50946. return this._to;
  50947. },
  50948. enumerable: true,
  50949. configurable: true
  50950. });
  50951. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50952. /**
  50953. * Define if the animations are started
  50954. */
  50955. get: function () {
  50956. return this._isStarted;
  50957. },
  50958. enumerable: true,
  50959. configurable: true
  50960. });
  50961. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50962. /**
  50963. * Gets or sets the speed ratio to use for all animations
  50964. */
  50965. get: function () {
  50966. return this._speedRatio;
  50967. },
  50968. /**
  50969. * Gets or sets the speed ratio to use for all animations
  50970. */
  50971. set: function (value) {
  50972. if (this._speedRatio === value) {
  50973. return;
  50974. }
  50975. this._speedRatio = value;
  50976. for (var index = 0; index < this._animatables.length; index++) {
  50977. var animatable = this._animatables[index];
  50978. animatable.speedRatio = this._speedRatio;
  50979. }
  50980. },
  50981. enumerable: true,
  50982. configurable: true
  50983. });
  50984. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50985. /**
  50986. * Gets the targeted animations for this animation group
  50987. */
  50988. get: function () {
  50989. return this._targetedAnimations;
  50990. },
  50991. enumerable: true,
  50992. configurable: true
  50993. });
  50994. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50995. /**
  50996. * returning the list of animatables controlled by this animation group.
  50997. */
  50998. get: function () {
  50999. return this._animatables;
  51000. },
  51001. enumerable: true,
  51002. configurable: true
  51003. });
  51004. /**
  51005. * Add an animation (with its target) in the group
  51006. * @param animation defines the animation we want to add
  51007. * @param target defines the target of the animation
  51008. * @returns the {BABYLON.TargetedAnimation} object
  51009. */
  51010. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51011. var targetedAnimation = {
  51012. animation: animation,
  51013. target: target
  51014. };
  51015. var keys = animation.getKeys();
  51016. if (this._from > keys[0].frame) {
  51017. this._from = keys[0].frame;
  51018. }
  51019. if (this._to < keys[keys.length - 1].frame) {
  51020. this._to = keys[keys.length - 1].frame;
  51021. }
  51022. this._targetedAnimations.push(targetedAnimation);
  51023. return targetedAnimation;
  51024. };
  51025. /**
  51026. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51027. * It can add constant keys at begin or end
  51028. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51029. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51030. */
  51031. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51032. if (beginFrame === void 0) { beginFrame = null; }
  51033. if (endFrame === void 0) { endFrame = null; }
  51034. if (beginFrame == null)
  51035. beginFrame = this._from;
  51036. if (endFrame == null)
  51037. endFrame = this._to;
  51038. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51039. var targetedAnimation = this._targetedAnimations[index];
  51040. var keys = targetedAnimation.animation.getKeys();
  51041. var startKey = keys[0];
  51042. var endKey = keys[keys.length - 1];
  51043. if (startKey.frame > beginFrame) {
  51044. var newKey = {
  51045. frame: beginFrame,
  51046. value: startKey.value,
  51047. inTangent: startKey.inTangent,
  51048. outTangent: startKey.outTangent,
  51049. interpolation: startKey.interpolation
  51050. };
  51051. keys.splice(0, 0, newKey);
  51052. }
  51053. if (endKey.frame < endFrame) {
  51054. var newKey = {
  51055. frame: endFrame,
  51056. value: endKey.value,
  51057. inTangent: endKey.outTangent,
  51058. outTangent: endKey.outTangent,
  51059. interpolation: endKey.interpolation
  51060. };
  51061. keys.push(newKey);
  51062. }
  51063. }
  51064. this._from = beginFrame;
  51065. this._to = endFrame;
  51066. return this;
  51067. };
  51068. /**
  51069. * Start all animations on given targets
  51070. * @param loop defines if animations must loop
  51071. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51072. * @param from defines the from key (optional)
  51073. * @param to defines the to key (optional)
  51074. * @returns the current animation group
  51075. */
  51076. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51077. var _this = this;
  51078. if (loop === void 0) { loop = false; }
  51079. if (speedRatio === void 0) { speedRatio = 1; }
  51080. if (this._isStarted || this._targetedAnimations.length === 0) {
  51081. return this;
  51082. }
  51083. var _loop_1 = function (targetedAnimation) {
  51084. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51085. animatable.onAnimationEnd = function () {
  51086. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51087. _this._checkAnimationGroupEnded(animatable);
  51088. };
  51089. this_1._animatables.push(animatable);
  51090. };
  51091. var this_1 = this;
  51092. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51093. var targetedAnimation = _a[_i];
  51094. _loop_1(targetedAnimation);
  51095. }
  51096. this._speedRatio = speedRatio;
  51097. this._isStarted = true;
  51098. return this;
  51099. };
  51100. /**
  51101. * Pause all animations
  51102. */
  51103. AnimationGroup.prototype.pause = function () {
  51104. if (!this._isStarted) {
  51105. return this;
  51106. }
  51107. for (var index = 0; index < this._animatables.length; index++) {
  51108. var animatable = this._animatables[index];
  51109. animatable.pause();
  51110. }
  51111. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51112. return this;
  51113. };
  51114. /**
  51115. * Play all animations to initial state
  51116. * This function will start() the animations if they were not started or will restart() them if they were paused
  51117. * @param loop defines if animations must loop
  51118. */
  51119. AnimationGroup.prototype.play = function (loop) {
  51120. // only if all animatables are ready and exist
  51121. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51122. if (loop !== undefined) {
  51123. for (var index = 0; index < this._animatables.length; index++) {
  51124. var animatable = this._animatables[index];
  51125. animatable.loopAnimation = loop;
  51126. }
  51127. }
  51128. this.restart();
  51129. }
  51130. else {
  51131. this.stop();
  51132. this.start(loop, this._speedRatio);
  51133. }
  51134. return this;
  51135. };
  51136. /**
  51137. * Reset all animations to initial state
  51138. */
  51139. AnimationGroup.prototype.reset = function () {
  51140. if (!this._isStarted) {
  51141. return this;
  51142. }
  51143. for (var index = 0; index < this._animatables.length; index++) {
  51144. var animatable = this._animatables[index];
  51145. animatable.reset();
  51146. }
  51147. return this;
  51148. };
  51149. /**
  51150. * Restart animations from key 0
  51151. */
  51152. AnimationGroup.prototype.restart = function () {
  51153. if (!this._isStarted) {
  51154. return this;
  51155. }
  51156. for (var index = 0; index < this._animatables.length; index++) {
  51157. var animatable = this._animatables[index];
  51158. animatable.restart();
  51159. }
  51160. return this;
  51161. };
  51162. /**
  51163. * Stop all animations
  51164. */
  51165. AnimationGroup.prototype.stop = function () {
  51166. if (!this._isStarted) {
  51167. return this;
  51168. }
  51169. var list = this._animatables.slice();
  51170. for (var index = 0; index < list.length; index++) {
  51171. list[index].stop();
  51172. }
  51173. this._isStarted = false;
  51174. return this;
  51175. };
  51176. /**
  51177. * Set animation weight for all animatables
  51178. * @param weight defines the weight to use
  51179. * @return the animationGroup
  51180. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51181. */
  51182. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51183. for (var index = 0; index < this._animatables.length; index++) {
  51184. var animatable = this._animatables[index];
  51185. animatable.weight = weight;
  51186. }
  51187. return this;
  51188. };
  51189. /**
  51190. * Synchronize and normalize all animatables with a source animatable
  51191. * @param root defines the root animatable to synchronize with
  51192. * @return the animationGroup
  51193. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51194. */
  51195. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51196. for (var index = 0; index < this._animatables.length; index++) {
  51197. var animatable = this._animatables[index];
  51198. animatable.syncWith(root);
  51199. }
  51200. return this;
  51201. };
  51202. /**
  51203. * Goes to a specific frame in this animation group
  51204. * @param frame the frame number to go to
  51205. * @return the animationGroup
  51206. */
  51207. AnimationGroup.prototype.goToFrame = function (frame) {
  51208. if (!this._isStarted) {
  51209. return this;
  51210. }
  51211. for (var index = 0; index < this._animatables.length; index++) {
  51212. var animatable = this._animatables[index];
  51213. animatable.goToFrame(frame);
  51214. }
  51215. return this;
  51216. };
  51217. /**
  51218. * Dispose all associated resources
  51219. */
  51220. AnimationGroup.prototype.dispose = function () {
  51221. this._targetedAnimations = [];
  51222. this._animatables = [];
  51223. var index = this._scene.animationGroups.indexOf(this);
  51224. if (index > -1) {
  51225. this._scene.animationGroups.splice(index, 1);
  51226. }
  51227. };
  51228. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51229. // animatable should be taken out of the array
  51230. var idx = this._animatables.indexOf(animatable);
  51231. if (idx > -1) {
  51232. this._animatables.splice(idx, 1);
  51233. }
  51234. // all animatables were removed? animation group ended!
  51235. if (this._animatables.length === 0) {
  51236. this._isStarted = false;
  51237. this.onAnimationGroupEndObservable.notifyObservers(this);
  51238. }
  51239. };
  51240. return AnimationGroup;
  51241. }());
  51242. BABYLON.AnimationGroup = AnimationGroup;
  51243. })(BABYLON || (BABYLON = {}));
  51244. //# sourceMappingURL=babylon.animationGroup.js.map
  51245. var BABYLON;
  51246. (function (BABYLON) {
  51247. // Static values to help the garbage collector
  51248. // Quaternion
  51249. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51250. // Vector3
  51251. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51252. // Vector2
  51253. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51254. // Size
  51255. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51256. // Color3
  51257. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51258. /**
  51259. * Defines a runtime animation
  51260. */
  51261. var RuntimeAnimation = /** @class */ (function () {
  51262. /**
  51263. * Create a new RuntimeAnimation object
  51264. * @param target defines the target of the animation
  51265. * @param animation defines the source animation object
  51266. * @param scene defines the hosting scene
  51267. * @param host defines the initiating Animatable
  51268. */
  51269. function RuntimeAnimation(target, animation, scene, host) {
  51270. var _this = this;
  51271. this._events = new Array();
  51272. /**
  51273. * The current frame of the runtime animation
  51274. */
  51275. this._currentFrame = 0;
  51276. /**
  51277. * The original value of the runtime animation
  51278. */
  51279. this._originalValue = new Array();
  51280. /**
  51281. * The offsets cache of the runtime animation
  51282. */
  51283. this._offsetsCache = {};
  51284. /**
  51285. * The high limits cache of the runtime animation
  51286. */
  51287. this._highLimitsCache = {};
  51288. /**
  51289. * Specifies if the runtime animation has been stopped
  51290. */
  51291. this._stopped = false;
  51292. /**
  51293. * The blending factor of the runtime animation
  51294. */
  51295. this._blendingFactor = 0;
  51296. /**
  51297. * The target path of the runtime animation
  51298. */
  51299. this._targetPath = "";
  51300. /**
  51301. * The weight of the runtime animation
  51302. */
  51303. this._weight = 1.0;
  51304. /**
  51305. * The ratio offset of the runtime animation
  51306. */
  51307. this._ratioOffset = 0;
  51308. /**
  51309. * The previous delay of the runtime animation
  51310. */
  51311. this._previousDelay = 0;
  51312. /**
  51313. * The previous ratio of the runtime animation
  51314. */
  51315. this._previousRatio = 0;
  51316. this._animation = animation;
  51317. this._target = target;
  51318. this._scene = scene;
  51319. this._host = host;
  51320. animation._runtimeAnimations.push(this);
  51321. // Cloning events locally
  51322. var events = animation.getEvents();
  51323. if (events && events.length > 0) {
  51324. events.forEach(function (e) {
  51325. _this._events.push(e._clone());
  51326. });
  51327. }
  51328. }
  51329. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51330. /**
  51331. * Gets the current frame of the runtime animation
  51332. */
  51333. get: function () {
  51334. return this._currentFrame;
  51335. },
  51336. enumerable: true,
  51337. configurable: true
  51338. });
  51339. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51340. /**
  51341. * Gets the weight of the runtime animation
  51342. */
  51343. get: function () {
  51344. return this._weight;
  51345. },
  51346. enumerable: true,
  51347. configurable: true
  51348. });
  51349. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51350. /**
  51351. * Gets the current value of the runtime animation
  51352. */
  51353. get: function () {
  51354. return this._currentValue;
  51355. },
  51356. enumerable: true,
  51357. configurable: true
  51358. });
  51359. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51360. /**
  51361. * Gets the target path of the runtime animation
  51362. */
  51363. get: function () {
  51364. return this._targetPath;
  51365. },
  51366. enumerable: true,
  51367. configurable: true
  51368. });
  51369. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51370. /**
  51371. * Gets the actual target of the runtime animation
  51372. */
  51373. get: function () {
  51374. return this._activeTarget;
  51375. },
  51376. enumerable: true,
  51377. configurable: true
  51378. });
  51379. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51380. /**
  51381. * Gets the animation from the runtime animation
  51382. */
  51383. get: function () {
  51384. return this._animation;
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. /**
  51390. * Resets the runtime animation to the beginning
  51391. * @param restoreOriginal defines whether to restore the target property to the original value
  51392. */
  51393. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51394. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51395. if (restoreOriginal) {
  51396. if (this._target instanceof Array) {
  51397. var index = 0;
  51398. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51399. var target = _a[_i];
  51400. if (this._originalValue[index] !== undefined) {
  51401. this._setValue(target, this._originalValue[index], -1);
  51402. }
  51403. index++;
  51404. }
  51405. }
  51406. else {
  51407. if (this._originalValue[0] !== undefined) {
  51408. this._setValue(this._target, this._originalValue[0], -1);
  51409. }
  51410. }
  51411. }
  51412. this._offsetsCache = {};
  51413. this._highLimitsCache = {};
  51414. this._currentFrame = 0;
  51415. this._blendingFactor = 0;
  51416. this._originalValue = new Array();
  51417. // Events
  51418. for (var index = 0; index < this._events.length; index++) {
  51419. this._events[index].isDone = false;
  51420. }
  51421. };
  51422. /**
  51423. * Specifies if the runtime animation is stopped
  51424. * @returns Boolean specifying if the runtime animation is stopped
  51425. */
  51426. RuntimeAnimation.prototype.isStopped = function () {
  51427. return this._stopped;
  51428. };
  51429. /**
  51430. * Disposes of the runtime animation
  51431. */
  51432. RuntimeAnimation.prototype.dispose = function () {
  51433. var index = this._animation.runtimeAnimations.indexOf(this);
  51434. if (index > -1) {
  51435. this._animation.runtimeAnimations.splice(index, 1);
  51436. }
  51437. };
  51438. /**
  51439. * Interpolates the animation from the current frame
  51440. * @param currentFrame The frame to interpolate the animation to
  51441. * @param repeatCount The number of times that the animation should loop
  51442. * @param loopMode The type of looping mode to use
  51443. * @param offsetValue Animation offset value
  51444. * @param highLimitValue The high limit value
  51445. * @returns The interpolated value
  51446. */
  51447. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51448. this._currentFrame = currentFrame;
  51449. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51450. this._workValue = BABYLON.Matrix.Zero();
  51451. }
  51452. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51453. };
  51454. /**
  51455. * Apply the interpolated value to the target
  51456. * @param currentValue defines the value computed by the animation
  51457. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51458. */
  51459. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51460. if (weight === void 0) { weight = 1.0; }
  51461. if (this._target instanceof Array) {
  51462. var index = 0;
  51463. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51464. var target = _a[_i];
  51465. this._setValue(target, currentValue, weight, index);
  51466. index++;
  51467. }
  51468. }
  51469. else {
  51470. this._setValue(this._target, currentValue, weight);
  51471. }
  51472. };
  51473. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51474. if (targetIndex === void 0) { targetIndex = 0; }
  51475. // Set value
  51476. var path;
  51477. var destination;
  51478. var targetPropertyPath = this._animation.targetPropertyPath;
  51479. if (targetPropertyPath.length > 1) {
  51480. var property = target[targetPropertyPath[0]];
  51481. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51482. property = property[targetPropertyPath[index]];
  51483. }
  51484. path = targetPropertyPath[targetPropertyPath.length - 1];
  51485. destination = property;
  51486. }
  51487. else {
  51488. path = targetPropertyPath[0];
  51489. destination = target;
  51490. }
  51491. this._targetPath = path;
  51492. this._activeTarget = destination;
  51493. this._weight = weight;
  51494. if (this._originalValue[targetIndex] === undefined) {
  51495. var originalValue = void 0;
  51496. if (destination.getRestPose && path === "_matrix") { // For bones
  51497. originalValue = destination.getRestPose();
  51498. }
  51499. else {
  51500. originalValue = destination[path];
  51501. }
  51502. if (originalValue && originalValue.clone) {
  51503. this._originalValue[targetIndex] = originalValue.clone();
  51504. }
  51505. else {
  51506. this._originalValue[targetIndex] = originalValue;
  51507. }
  51508. }
  51509. // Blending
  51510. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51511. if (enableBlending && this._blendingFactor <= 1.0) {
  51512. if (!this._originalBlendValue) {
  51513. var originalValue = destination[path];
  51514. if (originalValue.clone) {
  51515. this._originalBlendValue = originalValue.clone();
  51516. }
  51517. else {
  51518. this._originalBlendValue = originalValue;
  51519. }
  51520. }
  51521. if (this._originalBlendValue.m) { // Matrix
  51522. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51523. if (this._currentValue) {
  51524. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51525. }
  51526. else {
  51527. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51528. }
  51529. }
  51530. else {
  51531. if (this._currentValue) {
  51532. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51533. }
  51534. else {
  51535. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51536. }
  51537. }
  51538. }
  51539. else {
  51540. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51541. }
  51542. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51543. this._blendingFactor += blendingSpeed;
  51544. }
  51545. else {
  51546. this._currentValue = currentValue;
  51547. }
  51548. if (weight !== -1.0) {
  51549. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51550. }
  51551. else {
  51552. destination[path] = this._currentValue;
  51553. }
  51554. if (target.markAsDirty) {
  51555. target.markAsDirty(this._animation.targetProperty);
  51556. }
  51557. };
  51558. /**
  51559. * Gets the loop pmode of the runtime animation
  51560. * @returns Loop Mode
  51561. */
  51562. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51563. if (this._target && this._target.animationPropertiesOverride) {
  51564. return this._target.animationPropertiesOverride.loopMode;
  51565. }
  51566. return this._animation.loopMode;
  51567. };
  51568. /**
  51569. * Move the current animation to a given frame
  51570. * @param frame defines the frame to move to
  51571. */
  51572. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51573. var keys = this._animation.getKeys();
  51574. if (frame < keys[0].frame) {
  51575. frame = keys[0].frame;
  51576. }
  51577. else if (frame > keys[keys.length - 1].frame) {
  51578. frame = keys[keys.length - 1].frame;
  51579. }
  51580. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51581. this.setValue(currentValue, -1);
  51582. };
  51583. /**
  51584. * @hidden Internal use only
  51585. */
  51586. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51587. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51588. this._ratioOffset = this._previousRatio - newRatio;
  51589. };
  51590. /**
  51591. * Execute the current animation
  51592. * @param delay defines the delay to add to the current frame
  51593. * @param from defines the lower bound of the animation range
  51594. * @param to defines the upper bound of the animation range
  51595. * @param loop defines if the current animation must loop
  51596. * @param speedRatio defines the current speed ratio
  51597. * @param weight defines the weight of the animation (default is -1 so no weight)
  51598. * @returns a boolean indicating if the animation is running
  51599. */
  51600. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51601. if (weight === void 0) { weight = -1.0; }
  51602. var targetPropertyPath = this._animation.targetPropertyPath;
  51603. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51604. this._stopped = true;
  51605. return false;
  51606. }
  51607. var returnValue = true;
  51608. var keys = this._animation.getKeys();
  51609. // Adding a start key at frame 0 if missing
  51610. if (keys[0].frame !== 0) {
  51611. var newKey = { frame: 0, value: keys[0].value };
  51612. keys.splice(0, 0, newKey);
  51613. }
  51614. // Adding a duplicate key when there is only one key at frame zero
  51615. else if (keys.length === 1) {
  51616. var newKey = { frame: 0.001, value: keys[0].value };
  51617. keys.push(newKey);
  51618. }
  51619. // Check limits
  51620. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51621. from = keys[0].frame;
  51622. }
  51623. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51624. to = keys[keys.length - 1].frame;
  51625. }
  51626. //to and from cannot be the same key
  51627. if (from === to) {
  51628. if (from > keys[0].frame) {
  51629. from--;
  51630. }
  51631. else if (to < keys[keys.length - 1].frame) {
  51632. to++;
  51633. }
  51634. }
  51635. // Compute ratio
  51636. var range = to - from;
  51637. var offsetValue;
  51638. // ratio represents the frame delta between from and to
  51639. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51640. var highLimitValue = 0;
  51641. this._previousDelay = delay;
  51642. this._previousRatio = ratio;
  51643. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51644. returnValue = false;
  51645. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51646. }
  51647. else {
  51648. // Get max value if required
  51649. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51650. var keyOffset = to.toString() + from.toString();
  51651. if (!this._offsetsCache[keyOffset]) {
  51652. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51653. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51654. switch (this._animation.dataType) {
  51655. // Float
  51656. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51657. this._offsetsCache[keyOffset] = toValue - fromValue;
  51658. break;
  51659. // Quaternion
  51660. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51661. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51662. break;
  51663. // Vector3
  51664. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51665. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51666. // Vector2
  51667. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51668. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51669. // Size
  51670. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51671. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51672. // Color3
  51673. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51674. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51675. default:
  51676. break;
  51677. }
  51678. this._highLimitsCache[keyOffset] = toValue;
  51679. }
  51680. highLimitValue = this._highLimitsCache[keyOffset];
  51681. offsetValue = this._offsetsCache[keyOffset];
  51682. }
  51683. }
  51684. if (offsetValue === undefined) {
  51685. switch (this._animation.dataType) {
  51686. // Float
  51687. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51688. offsetValue = 0;
  51689. break;
  51690. // Quaternion
  51691. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51692. offsetValue = _staticOffsetValueQuaternion;
  51693. break;
  51694. // Vector3
  51695. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51696. offsetValue = _staticOffsetValueVector3;
  51697. break;
  51698. // Vector2
  51699. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51700. offsetValue = _staticOffsetValueVector2;
  51701. break;
  51702. // Size
  51703. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51704. offsetValue = _staticOffsetValueSize;
  51705. break;
  51706. // Color3
  51707. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51708. offsetValue = _staticOffsetValueColor3;
  51709. }
  51710. }
  51711. // Compute value
  51712. var repeatCount = (ratio / range) >> 0;
  51713. var currentFrame = returnValue ? from + ratio % range : to;
  51714. // Need to normalize?
  51715. if (this._host && this._host.syncRoot) {
  51716. var syncRoot = this._host.syncRoot;
  51717. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51718. currentFrame = from + (to - from) * hostNormalizedFrame;
  51719. }
  51720. // Reset events if looping
  51721. var events = this._events;
  51722. if (range > 0 && this.currentFrame > currentFrame ||
  51723. range < 0 && this.currentFrame < currentFrame) {
  51724. // Need to reset animation events
  51725. for (var index = 0; index < events.length; index++) {
  51726. if (!events[index].onlyOnce) {
  51727. // reset event, the animation is looping
  51728. events[index].isDone = false;
  51729. }
  51730. }
  51731. }
  51732. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51733. // Set value
  51734. this.setValue(currentValue, weight);
  51735. // Check events
  51736. for (var index = 0; index < events.length; index++) {
  51737. // Make sure current frame has passed event frame and that event frame is within the current range
  51738. // Also, handle both forward and reverse animations
  51739. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51740. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51741. var event = events[index];
  51742. if (!event.isDone) {
  51743. // If event should be done only once, remove it.
  51744. if (event.onlyOnce) {
  51745. events.splice(index, 1);
  51746. index--;
  51747. }
  51748. event.isDone = true;
  51749. event.action(currentFrame);
  51750. } // Don't do anything if the event has already be done.
  51751. }
  51752. }
  51753. if (!returnValue) {
  51754. this._stopped = true;
  51755. }
  51756. return returnValue;
  51757. };
  51758. return RuntimeAnimation;
  51759. }());
  51760. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51761. })(BABYLON || (BABYLON = {}));
  51762. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51763. var BABYLON;
  51764. (function (BABYLON) {
  51765. /**
  51766. * Class used to store an actual running animation
  51767. */
  51768. var Animatable = /** @class */ (function () {
  51769. /**
  51770. * Creates a new Animatable
  51771. * @param scene defines the hosting scene
  51772. * @param target defines the target object
  51773. * @param fromFrame defines the starting frame number (default is 0)
  51774. * @param toFrame defines the ending frame number (default is 100)
  51775. * @param loopAnimation defines if the animation must loop (default is false)
  51776. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51777. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51778. * @param animations defines a group of animation to add to the new Animatable
  51779. */
  51780. function Animatable(scene,
  51781. /** defines the target object */
  51782. target,
  51783. /** defines the starting frame number (default is 0) */
  51784. fromFrame,
  51785. /** defines the ending frame number (default is 100) */
  51786. toFrame,
  51787. /** defines if the animation must loop (default is false) */
  51788. loopAnimation, speedRatio,
  51789. /** defines a callback to call when animation ends if it is not looping */
  51790. onAnimationEnd, animations) {
  51791. if (fromFrame === void 0) { fromFrame = 0; }
  51792. if (toFrame === void 0) { toFrame = 100; }
  51793. if (loopAnimation === void 0) { loopAnimation = false; }
  51794. if (speedRatio === void 0) { speedRatio = 1.0; }
  51795. this.target = target;
  51796. this.fromFrame = fromFrame;
  51797. this.toFrame = toFrame;
  51798. this.loopAnimation = loopAnimation;
  51799. this.onAnimationEnd = onAnimationEnd;
  51800. this._localDelayOffset = null;
  51801. this._pausedDelay = null;
  51802. this._runtimeAnimations = new Array();
  51803. this._paused = false;
  51804. this._speedRatio = 1;
  51805. this._weight = -1.0;
  51806. /**
  51807. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51808. * This will only apply for non looping animation (default is true)
  51809. */
  51810. this.disposeOnEnd = true;
  51811. /**
  51812. * Gets a boolean indicating if the animation has started
  51813. */
  51814. this.animationStarted = false;
  51815. /**
  51816. * Observer raised when the animation ends
  51817. */
  51818. this.onAnimationEndObservable = new BABYLON.Observable();
  51819. this._scene = scene;
  51820. if (animations) {
  51821. this.appendAnimations(target, animations);
  51822. }
  51823. this._speedRatio = speedRatio;
  51824. scene._activeAnimatables.push(this);
  51825. }
  51826. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51827. /**
  51828. * Gets the root Animatable used to synchronize and normalize animations
  51829. */
  51830. get: function () {
  51831. return this._syncRoot;
  51832. },
  51833. enumerable: true,
  51834. configurable: true
  51835. });
  51836. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51837. /**
  51838. * Gets the current frame of the first RuntimeAnimation
  51839. * Used to synchronize Animatables
  51840. */
  51841. get: function () {
  51842. if (this._runtimeAnimations.length === 0) {
  51843. return 0;
  51844. }
  51845. return this._runtimeAnimations[0].currentFrame;
  51846. },
  51847. enumerable: true,
  51848. configurable: true
  51849. });
  51850. Object.defineProperty(Animatable.prototype, "weight", {
  51851. /**
  51852. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51853. */
  51854. get: function () {
  51855. return this._weight;
  51856. },
  51857. set: function (value) {
  51858. if (value === -1) { // -1 is ok and means no weight
  51859. this._weight = -1;
  51860. return;
  51861. }
  51862. // Else weight must be in [0, 1] range
  51863. this._weight = Math.min(Math.max(value, 0), 1.0);
  51864. },
  51865. enumerable: true,
  51866. configurable: true
  51867. });
  51868. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51869. /**
  51870. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51871. */
  51872. get: function () {
  51873. return this._speedRatio;
  51874. },
  51875. set: function (value) {
  51876. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51877. var animation = this._runtimeAnimations[index];
  51878. animation._prepareForSpeedRatioChange(value);
  51879. }
  51880. this._speedRatio = value;
  51881. },
  51882. enumerable: true,
  51883. configurable: true
  51884. });
  51885. // Methods
  51886. /**
  51887. * Synchronize and normalize current Animatable with a source Animatable
  51888. * This is useful when using animation weights and when animations are not of the same length
  51889. * @param root defines the root Animatable to synchronize with
  51890. * @returns the current Animatable
  51891. */
  51892. Animatable.prototype.syncWith = function (root) {
  51893. this._syncRoot = root;
  51894. if (root) {
  51895. // Make sure this animatable will animate after the root
  51896. var index = this._scene._activeAnimatables.indexOf(this);
  51897. if (index > -1) {
  51898. this._scene._activeAnimatables.splice(index, 1);
  51899. this._scene._activeAnimatables.push(this);
  51900. }
  51901. }
  51902. return this;
  51903. };
  51904. /**
  51905. * Gets the list of runtime animations
  51906. * @returns an array of RuntimeAnimation
  51907. */
  51908. Animatable.prototype.getAnimations = function () {
  51909. return this._runtimeAnimations;
  51910. };
  51911. /**
  51912. * Adds more animations to the current animatable
  51913. * @param target defines the target of the animations
  51914. * @param animations defines the new animations to add
  51915. */
  51916. Animatable.prototype.appendAnimations = function (target, animations) {
  51917. for (var index = 0; index < animations.length; index++) {
  51918. var animation = animations[index];
  51919. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51920. }
  51921. };
  51922. /**
  51923. * Gets the source animation for a specific property
  51924. * @param property defines the propertyu to look for
  51925. * @returns null or the source animation for the given property
  51926. */
  51927. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51928. var runtimeAnimations = this._runtimeAnimations;
  51929. for (var index = 0; index < runtimeAnimations.length; index++) {
  51930. if (runtimeAnimations[index].animation.targetProperty === property) {
  51931. return runtimeAnimations[index].animation;
  51932. }
  51933. }
  51934. return null;
  51935. };
  51936. /**
  51937. * Gets the runtime animation for a specific property
  51938. * @param property defines the propertyu to look for
  51939. * @returns null or the runtime animation for the given property
  51940. */
  51941. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51942. var runtimeAnimations = this._runtimeAnimations;
  51943. for (var index = 0; index < runtimeAnimations.length; index++) {
  51944. if (runtimeAnimations[index].animation.targetProperty === property) {
  51945. return runtimeAnimations[index];
  51946. }
  51947. }
  51948. return null;
  51949. };
  51950. /**
  51951. * Resets the animatable to its original state
  51952. */
  51953. Animatable.prototype.reset = function () {
  51954. var runtimeAnimations = this._runtimeAnimations;
  51955. for (var index = 0; index < runtimeAnimations.length; index++) {
  51956. runtimeAnimations[index].reset(true);
  51957. }
  51958. this._localDelayOffset = null;
  51959. this._pausedDelay = null;
  51960. };
  51961. /**
  51962. * Allows the animatable to blend with current running animations
  51963. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51964. * @param blendingSpeed defines the blending speed to use
  51965. */
  51966. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51967. var runtimeAnimations = this._runtimeAnimations;
  51968. for (var index = 0; index < runtimeAnimations.length; index++) {
  51969. runtimeAnimations[index].animation.enableBlending = true;
  51970. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51971. }
  51972. };
  51973. /**
  51974. * Disable animation blending
  51975. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51976. */
  51977. Animatable.prototype.disableBlending = function () {
  51978. var runtimeAnimations = this._runtimeAnimations;
  51979. for (var index = 0; index < runtimeAnimations.length; index++) {
  51980. runtimeAnimations[index].animation.enableBlending = false;
  51981. }
  51982. };
  51983. /**
  51984. * Jump directly to a given frame
  51985. * @param frame defines the frame to jump to
  51986. */
  51987. Animatable.prototype.goToFrame = function (frame) {
  51988. var runtimeAnimations = this._runtimeAnimations;
  51989. if (runtimeAnimations[0]) {
  51990. var fps = runtimeAnimations[0].animation.framePerSecond;
  51991. var currentFrame = runtimeAnimations[0].currentFrame;
  51992. var adjustTime = frame - currentFrame;
  51993. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51994. if (this._localDelayOffset === null) {
  51995. this._localDelayOffset = 0;
  51996. }
  51997. this._localDelayOffset -= delay;
  51998. }
  51999. for (var index = 0; index < runtimeAnimations.length; index++) {
  52000. runtimeAnimations[index].goToFrame(frame);
  52001. }
  52002. };
  52003. /**
  52004. * Pause the animation
  52005. */
  52006. Animatable.prototype.pause = function () {
  52007. if (this._paused) {
  52008. return;
  52009. }
  52010. this._paused = true;
  52011. };
  52012. /**
  52013. * Restart the animation
  52014. */
  52015. Animatable.prototype.restart = function () {
  52016. this._paused = false;
  52017. };
  52018. Animatable.prototype._raiseOnAnimationEnd = function () {
  52019. if (this.onAnimationEnd) {
  52020. this.onAnimationEnd();
  52021. }
  52022. this.onAnimationEndObservable.notifyObservers(this);
  52023. };
  52024. /**
  52025. * Stop and delete the current animation
  52026. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52027. * @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)
  52028. */
  52029. Animatable.prototype.stop = function (animationName, targetMask) {
  52030. if (animationName || targetMask) {
  52031. var idx = this._scene._activeAnimatables.indexOf(this);
  52032. if (idx > -1) {
  52033. var runtimeAnimations = this._runtimeAnimations;
  52034. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52035. var runtimeAnimation = runtimeAnimations[index];
  52036. if (animationName && runtimeAnimation.animation.name != animationName) {
  52037. continue;
  52038. }
  52039. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52040. continue;
  52041. }
  52042. runtimeAnimation.dispose();
  52043. runtimeAnimations.splice(index, 1);
  52044. }
  52045. if (runtimeAnimations.length == 0) {
  52046. this._scene._activeAnimatables.splice(idx, 1);
  52047. this._raiseOnAnimationEnd();
  52048. }
  52049. }
  52050. }
  52051. else {
  52052. var index = this._scene._activeAnimatables.indexOf(this);
  52053. if (index > -1) {
  52054. this._scene._activeAnimatables.splice(index, 1);
  52055. var runtimeAnimations = this._runtimeAnimations;
  52056. for (var index = 0; index < runtimeAnimations.length; index++) {
  52057. runtimeAnimations[index].dispose();
  52058. }
  52059. this._raiseOnAnimationEnd();
  52060. }
  52061. }
  52062. };
  52063. /**
  52064. * Wait asynchronously for the animation to end
  52065. * @returns a promise which will be fullfilled when the animation ends
  52066. */
  52067. Animatable.prototype.waitAsync = function () {
  52068. var _this = this;
  52069. return new Promise(function (resolve, reject) {
  52070. _this.onAnimationEndObservable.add(function () {
  52071. resolve(_this);
  52072. }, undefined, undefined, _this, true);
  52073. });
  52074. };
  52075. /** @hidden */
  52076. Animatable.prototype._animate = function (delay) {
  52077. if (this._paused) {
  52078. this.animationStarted = false;
  52079. if (this._pausedDelay === null) {
  52080. this._pausedDelay = delay;
  52081. }
  52082. return true;
  52083. }
  52084. if (this._localDelayOffset === null) {
  52085. this._localDelayOffset = delay;
  52086. this._pausedDelay = null;
  52087. }
  52088. else if (this._pausedDelay !== null) {
  52089. this._localDelayOffset += delay - this._pausedDelay;
  52090. this._pausedDelay = null;
  52091. }
  52092. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52093. return true;
  52094. }
  52095. // Animating
  52096. var running = false;
  52097. var runtimeAnimations = this._runtimeAnimations;
  52098. var index;
  52099. for (index = 0; index < runtimeAnimations.length; index++) {
  52100. var animation = runtimeAnimations[index];
  52101. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52102. running = running || isRunning;
  52103. }
  52104. this.animationStarted = running;
  52105. if (!running) {
  52106. if (this.disposeOnEnd) {
  52107. // Remove from active animatables
  52108. index = this._scene._activeAnimatables.indexOf(this);
  52109. this._scene._activeAnimatables.splice(index, 1);
  52110. // Dispose all runtime animations
  52111. for (index = 0; index < runtimeAnimations.length; index++) {
  52112. runtimeAnimations[index].dispose();
  52113. }
  52114. }
  52115. this._raiseOnAnimationEnd();
  52116. if (this.disposeOnEnd) {
  52117. this.onAnimationEnd = null;
  52118. this.onAnimationEndObservable.clear();
  52119. }
  52120. }
  52121. return running;
  52122. };
  52123. return Animatable;
  52124. }());
  52125. BABYLON.Animatable = Animatable;
  52126. })(BABYLON || (BABYLON = {}));
  52127. //# sourceMappingURL=babylon.animatable.js.map
  52128. var BABYLON;
  52129. (function (BABYLON) {
  52130. var EasingFunction = /** @class */ (function () {
  52131. function EasingFunction() {
  52132. // Properties
  52133. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52134. }
  52135. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52136. get: function () {
  52137. return EasingFunction._EASINGMODE_EASEIN;
  52138. },
  52139. enumerable: true,
  52140. configurable: true
  52141. });
  52142. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52143. get: function () {
  52144. return EasingFunction._EASINGMODE_EASEOUT;
  52145. },
  52146. enumerable: true,
  52147. configurable: true
  52148. });
  52149. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52150. get: function () {
  52151. return EasingFunction._EASINGMODE_EASEINOUT;
  52152. },
  52153. enumerable: true,
  52154. configurable: true
  52155. });
  52156. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52157. var n = Math.min(Math.max(easingMode, 0), 2);
  52158. this._easingMode = n;
  52159. };
  52160. EasingFunction.prototype.getEasingMode = function () {
  52161. return this._easingMode;
  52162. };
  52163. EasingFunction.prototype.easeInCore = function (gradient) {
  52164. throw new Error('You must implement this method');
  52165. };
  52166. EasingFunction.prototype.ease = function (gradient) {
  52167. switch (this._easingMode) {
  52168. case EasingFunction.EASINGMODE_EASEIN:
  52169. return this.easeInCore(gradient);
  52170. case EasingFunction.EASINGMODE_EASEOUT:
  52171. return (1 - this.easeInCore(1 - gradient));
  52172. }
  52173. if (gradient >= 0.5) {
  52174. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52175. }
  52176. return (this.easeInCore(gradient * 2) * 0.5);
  52177. };
  52178. //Statics
  52179. EasingFunction._EASINGMODE_EASEIN = 0;
  52180. EasingFunction._EASINGMODE_EASEOUT = 1;
  52181. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52182. return EasingFunction;
  52183. }());
  52184. BABYLON.EasingFunction = EasingFunction;
  52185. var CircleEase = /** @class */ (function (_super) {
  52186. __extends(CircleEase, _super);
  52187. function CircleEase() {
  52188. return _super !== null && _super.apply(this, arguments) || this;
  52189. }
  52190. CircleEase.prototype.easeInCore = function (gradient) {
  52191. gradient = Math.max(0, Math.min(1, gradient));
  52192. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52193. };
  52194. return CircleEase;
  52195. }(EasingFunction));
  52196. BABYLON.CircleEase = CircleEase;
  52197. var BackEase = /** @class */ (function (_super) {
  52198. __extends(BackEase, _super);
  52199. function BackEase(amplitude) {
  52200. if (amplitude === void 0) { amplitude = 1; }
  52201. var _this = _super.call(this) || this;
  52202. _this.amplitude = amplitude;
  52203. return _this;
  52204. }
  52205. BackEase.prototype.easeInCore = function (gradient) {
  52206. var num = Math.max(0, this.amplitude);
  52207. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52208. };
  52209. return BackEase;
  52210. }(EasingFunction));
  52211. BABYLON.BackEase = BackEase;
  52212. var BounceEase = /** @class */ (function (_super) {
  52213. __extends(BounceEase, _super);
  52214. function BounceEase(bounces, bounciness) {
  52215. if (bounces === void 0) { bounces = 3; }
  52216. if (bounciness === void 0) { bounciness = 2; }
  52217. var _this = _super.call(this) || this;
  52218. _this.bounces = bounces;
  52219. _this.bounciness = bounciness;
  52220. return _this;
  52221. }
  52222. BounceEase.prototype.easeInCore = function (gradient) {
  52223. var y = Math.max(0.0, this.bounces);
  52224. var bounciness = this.bounciness;
  52225. if (bounciness <= 1.0) {
  52226. bounciness = 1.001;
  52227. }
  52228. var num9 = Math.pow(bounciness, y);
  52229. var num5 = 1.0 - bounciness;
  52230. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52231. var num15 = gradient * num4;
  52232. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52233. var num3 = Math.floor(num65);
  52234. var num13 = num3 + 1.0;
  52235. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52236. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52237. var num7 = (num8 + num12) * 0.5;
  52238. var num6 = gradient - num7;
  52239. var num2 = num7 - num8;
  52240. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52241. };
  52242. return BounceEase;
  52243. }(EasingFunction));
  52244. BABYLON.BounceEase = BounceEase;
  52245. var CubicEase = /** @class */ (function (_super) {
  52246. __extends(CubicEase, _super);
  52247. function CubicEase() {
  52248. return _super !== null && _super.apply(this, arguments) || this;
  52249. }
  52250. CubicEase.prototype.easeInCore = function (gradient) {
  52251. return (gradient * gradient * gradient);
  52252. };
  52253. return CubicEase;
  52254. }(EasingFunction));
  52255. BABYLON.CubicEase = CubicEase;
  52256. var ElasticEase = /** @class */ (function (_super) {
  52257. __extends(ElasticEase, _super);
  52258. function ElasticEase(oscillations, springiness) {
  52259. if (oscillations === void 0) { oscillations = 3; }
  52260. if (springiness === void 0) { springiness = 3; }
  52261. var _this = _super.call(this) || this;
  52262. _this.oscillations = oscillations;
  52263. _this.springiness = springiness;
  52264. return _this;
  52265. }
  52266. ElasticEase.prototype.easeInCore = function (gradient) {
  52267. var num2;
  52268. var num3 = Math.max(0.0, this.oscillations);
  52269. var num = Math.max(0.0, this.springiness);
  52270. if (num == 0) {
  52271. num2 = gradient;
  52272. }
  52273. else {
  52274. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52275. }
  52276. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52277. };
  52278. return ElasticEase;
  52279. }(EasingFunction));
  52280. BABYLON.ElasticEase = ElasticEase;
  52281. var ExponentialEase = /** @class */ (function (_super) {
  52282. __extends(ExponentialEase, _super);
  52283. function ExponentialEase(exponent) {
  52284. if (exponent === void 0) { exponent = 2; }
  52285. var _this = _super.call(this) || this;
  52286. _this.exponent = exponent;
  52287. return _this;
  52288. }
  52289. ExponentialEase.prototype.easeInCore = function (gradient) {
  52290. if (this.exponent <= 0) {
  52291. return gradient;
  52292. }
  52293. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52294. };
  52295. return ExponentialEase;
  52296. }(EasingFunction));
  52297. BABYLON.ExponentialEase = ExponentialEase;
  52298. var PowerEase = /** @class */ (function (_super) {
  52299. __extends(PowerEase, _super);
  52300. function PowerEase(power) {
  52301. if (power === void 0) { power = 2; }
  52302. var _this = _super.call(this) || this;
  52303. _this.power = power;
  52304. return _this;
  52305. }
  52306. PowerEase.prototype.easeInCore = function (gradient) {
  52307. var y = Math.max(0.0, this.power);
  52308. return Math.pow(gradient, y);
  52309. };
  52310. return PowerEase;
  52311. }(EasingFunction));
  52312. BABYLON.PowerEase = PowerEase;
  52313. var QuadraticEase = /** @class */ (function (_super) {
  52314. __extends(QuadraticEase, _super);
  52315. function QuadraticEase() {
  52316. return _super !== null && _super.apply(this, arguments) || this;
  52317. }
  52318. QuadraticEase.prototype.easeInCore = function (gradient) {
  52319. return (gradient * gradient);
  52320. };
  52321. return QuadraticEase;
  52322. }(EasingFunction));
  52323. BABYLON.QuadraticEase = QuadraticEase;
  52324. var QuarticEase = /** @class */ (function (_super) {
  52325. __extends(QuarticEase, _super);
  52326. function QuarticEase() {
  52327. return _super !== null && _super.apply(this, arguments) || this;
  52328. }
  52329. QuarticEase.prototype.easeInCore = function (gradient) {
  52330. return (gradient * gradient * gradient * gradient);
  52331. };
  52332. return QuarticEase;
  52333. }(EasingFunction));
  52334. BABYLON.QuarticEase = QuarticEase;
  52335. var QuinticEase = /** @class */ (function (_super) {
  52336. __extends(QuinticEase, _super);
  52337. function QuinticEase() {
  52338. return _super !== null && _super.apply(this, arguments) || this;
  52339. }
  52340. QuinticEase.prototype.easeInCore = function (gradient) {
  52341. return (gradient * gradient * gradient * gradient * gradient);
  52342. };
  52343. return QuinticEase;
  52344. }(EasingFunction));
  52345. BABYLON.QuinticEase = QuinticEase;
  52346. var SineEase = /** @class */ (function (_super) {
  52347. __extends(SineEase, _super);
  52348. function SineEase() {
  52349. return _super !== null && _super.apply(this, arguments) || this;
  52350. }
  52351. SineEase.prototype.easeInCore = function (gradient) {
  52352. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52353. };
  52354. return SineEase;
  52355. }(EasingFunction));
  52356. BABYLON.SineEase = SineEase;
  52357. var BezierCurveEase = /** @class */ (function (_super) {
  52358. __extends(BezierCurveEase, _super);
  52359. function BezierCurveEase(x1, y1, x2, y2) {
  52360. if (x1 === void 0) { x1 = 0; }
  52361. if (y1 === void 0) { y1 = 0; }
  52362. if (x2 === void 0) { x2 = 1; }
  52363. if (y2 === void 0) { y2 = 1; }
  52364. var _this = _super.call(this) || this;
  52365. _this.x1 = x1;
  52366. _this.y1 = y1;
  52367. _this.x2 = x2;
  52368. _this.y2 = y2;
  52369. return _this;
  52370. }
  52371. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52372. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52373. };
  52374. return BezierCurveEase;
  52375. }(EasingFunction));
  52376. BABYLON.BezierCurveEase = BezierCurveEase;
  52377. })(BABYLON || (BABYLON = {}));
  52378. //# sourceMappingURL=babylon.easing.js.map
  52379. var BABYLON;
  52380. (function (BABYLON) {
  52381. /**
  52382. * A Condition applied to an Action
  52383. */
  52384. var Condition = /** @class */ (function () {
  52385. /**
  52386. * Creates a new Condition
  52387. * @param actionManager the manager of the action the condition is applied to
  52388. */
  52389. function Condition(actionManager) {
  52390. this._actionManager = actionManager;
  52391. }
  52392. /**
  52393. * Check if the current condition is valid
  52394. * @returns a boolean
  52395. */
  52396. Condition.prototype.isValid = function () {
  52397. return true;
  52398. };
  52399. /**
  52400. * Internal only
  52401. * @hidden
  52402. */
  52403. Condition.prototype._getProperty = function (propertyPath) {
  52404. return this._actionManager._getProperty(propertyPath);
  52405. };
  52406. /**
  52407. * Internal only
  52408. * @hidden
  52409. */
  52410. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52411. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52412. };
  52413. /**
  52414. * Serialize placeholder for child classes
  52415. * @returns the serialized object
  52416. */
  52417. Condition.prototype.serialize = function () {
  52418. };
  52419. /**
  52420. * Internal only
  52421. * @hidden
  52422. */
  52423. Condition.prototype._serialize = function (serializedCondition) {
  52424. return {
  52425. type: 2,
  52426. children: [],
  52427. name: serializedCondition.name,
  52428. properties: serializedCondition.properties
  52429. };
  52430. };
  52431. return Condition;
  52432. }());
  52433. BABYLON.Condition = Condition;
  52434. /**
  52435. * Defines specific conditional operators as extensions of Condition
  52436. */
  52437. var ValueCondition = /** @class */ (function (_super) {
  52438. __extends(ValueCondition, _super);
  52439. /**
  52440. * Creates a new ValueCondition
  52441. * @param actionManager manager for the action the condition applies to
  52442. * @param target for the action
  52443. * @param propertyPath path to specify the property of the target the conditional operator uses
  52444. * @param value the value compared by the conditional operator against the current value of the property
  52445. * @param operator the conditional operator, default ValueCondition.IsEqual
  52446. */
  52447. function ValueCondition(actionManager, target,
  52448. /** path to specify the property of the target the conditional operator uses */
  52449. propertyPath,
  52450. /** the value compared by the conditional operator against the current value of the property */
  52451. value,
  52452. /** the conditional operator, default ValueCondition.IsEqual */
  52453. operator) {
  52454. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52455. var _this = _super.call(this, actionManager) || this;
  52456. _this.propertyPath = propertyPath;
  52457. _this.value = value;
  52458. _this.operator = operator;
  52459. _this._target = target;
  52460. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52461. _this._property = _this._getProperty(_this.propertyPath);
  52462. return _this;
  52463. }
  52464. Object.defineProperty(ValueCondition, "IsEqual", {
  52465. /**
  52466. * returns the number for IsEqual
  52467. */
  52468. get: function () {
  52469. return ValueCondition._IsEqual;
  52470. },
  52471. enumerable: true,
  52472. configurable: true
  52473. });
  52474. Object.defineProperty(ValueCondition, "IsDifferent", {
  52475. /**
  52476. * Returns the number for IsDifferent
  52477. */
  52478. get: function () {
  52479. return ValueCondition._IsDifferent;
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. Object.defineProperty(ValueCondition, "IsGreater", {
  52485. /**
  52486. * Returns the number for IsGreater
  52487. */
  52488. get: function () {
  52489. return ValueCondition._IsGreater;
  52490. },
  52491. enumerable: true,
  52492. configurable: true
  52493. });
  52494. Object.defineProperty(ValueCondition, "IsLesser", {
  52495. /**
  52496. * Returns the number for IsLesser
  52497. */
  52498. get: function () {
  52499. return ValueCondition._IsLesser;
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. /**
  52505. * Compares the given value with the property value for the specified conditional operator
  52506. * @returns the result of the comparison
  52507. */
  52508. ValueCondition.prototype.isValid = function () {
  52509. switch (this.operator) {
  52510. case ValueCondition.IsGreater:
  52511. return this._effectiveTarget[this._property] > this.value;
  52512. case ValueCondition.IsLesser:
  52513. return this._effectiveTarget[this._property] < this.value;
  52514. case ValueCondition.IsEqual:
  52515. case ValueCondition.IsDifferent:
  52516. var check;
  52517. if (this.value.equals) {
  52518. check = this.value.equals(this._effectiveTarget[this._property]);
  52519. }
  52520. else {
  52521. check = this.value === this._effectiveTarget[this._property];
  52522. }
  52523. return this.operator === ValueCondition.IsEqual ? check : !check;
  52524. }
  52525. return false;
  52526. };
  52527. /**
  52528. * Serialize the ValueCondition into a JSON compatible object
  52529. * @returns serialization object
  52530. */
  52531. ValueCondition.prototype.serialize = function () {
  52532. return this._serialize({
  52533. name: "ValueCondition",
  52534. properties: [
  52535. BABYLON.Action._GetTargetProperty(this._target),
  52536. { name: "propertyPath", value: this.propertyPath },
  52537. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52538. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52539. ]
  52540. });
  52541. };
  52542. /**
  52543. * Gets the name of the conditional operator for the ValueCondition
  52544. * @param operator the conditional operator
  52545. * @returns the name
  52546. */
  52547. ValueCondition.GetOperatorName = function (operator) {
  52548. switch (operator) {
  52549. case ValueCondition._IsEqual: return "IsEqual";
  52550. case ValueCondition._IsDifferent: return "IsDifferent";
  52551. case ValueCondition._IsGreater: return "IsGreater";
  52552. case ValueCondition._IsLesser: return "IsLesser";
  52553. default: return "";
  52554. }
  52555. };
  52556. /**
  52557. * Internal only
  52558. * @hidden
  52559. */
  52560. ValueCondition._IsEqual = 0;
  52561. /**
  52562. * Internal only
  52563. * @hidden
  52564. */
  52565. ValueCondition._IsDifferent = 1;
  52566. /**
  52567. * Internal only
  52568. * @hidden
  52569. */
  52570. ValueCondition._IsGreater = 2;
  52571. /**
  52572. * Internal only
  52573. * @hidden
  52574. */
  52575. ValueCondition._IsLesser = 3;
  52576. return ValueCondition;
  52577. }(Condition));
  52578. BABYLON.ValueCondition = ValueCondition;
  52579. /**
  52580. * Defines a predicate condition as an extension of Condition
  52581. */
  52582. var PredicateCondition = /** @class */ (function (_super) {
  52583. __extends(PredicateCondition, _super);
  52584. /**
  52585. * Creates a new PredicateCondition
  52586. * @param actionManager manager for the action the condition applies to
  52587. * @param predicate defines the predicate function used to validate the condition
  52588. */
  52589. function PredicateCondition(actionManager,
  52590. /** defines the predicate function used to validate the condition */
  52591. predicate) {
  52592. var _this = _super.call(this, actionManager) || this;
  52593. _this.predicate = predicate;
  52594. return _this;
  52595. }
  52596. /**
  52597. * @returns the validity of the predicate condition
  52598. */
  52599. PredicateCondition.prototype.isValid = function () {
  52600. return this.predicate();
  52601. };
  52602. return PredicateCondition;
  52603. }(Condition));
  52604. BABYLON.PredicateCondition = PredicateCondition;
  52605. /**
  52606. * Defines a state condition as an extension of Condition
  52607. */
  52608. var StateCondition = /** @class */ (function (_super) {
  52609. __extends(StateCondition, _super);
  52610. /**
  52611. * Creates a new StateCondition
  52612. * @param actionManager manager for the action the condition applies to
  52613. * @param target of the condition
  52614. * @param value to compare with target state
  52615. */
  52616. function StateCondition(actionManager, target, value) {
  52617. var _this = _super.call(this, actionManager) || this;
  52618. _this.value = value;
  52619. _this._target = target;
  52620. return _this;
  52621. }
  52622. /**
  52623. * @returns the validity of the state
  52624. */
  52625. StateCondition.prototype.isValid = function () {
  52626. return this._target.state === this.value;
  52627. };
  52628. /**
  52629. * Serialize the StateCondition into a JSON compatible object
  52630. * @returns serialization object
  52631. */
  52632. StateCondition.prototype.serialize = function () {
  52633. return this._serialize({
  52634. name: "StateCondition",
  52635. properties: [
  52636. BABYLON.Action._GetTargetProperty(this._target),
  52637. { name: "value", value: this.value }
  52638. ]
  52639. });
  52640. };
  52641. return StateCondition;
  52642. }(Condition));
  52643. BABYLON.StateCondition = StateCondition;
  52644. })(BABYLON || (BABYLON = {}));
  52645. //# sourceMappingURL=babylon.condition.js.map
  52646. var BABYLON;
  52647. (function (BABYLON) {
  52648. /**
  52649. * The action to be carried out following a trigger
  52650. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52651. */
  52652. var Action = /** @class */ (function () {
  52653. /**
  52654. * Creates a new Action
  52655. * @param triggerOptions the trigger, with or without parameters, for the action
  52656. * @param condition an optional determinant of action
  52657. */
  52658. function Action(
  52659. /** the trigger, with or without parameters, for the action */
  52660. triggerOptions, condition) {
  52661. this.triggerOptions = triggerOptions;
  52662. /**
  52663. * An event triggered prior to action being executed.
  52664. */
  52665. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52666. if (triggerOptions.parameter) {
  52667. this.trigger = triggerOptions.trigger;
  52668. this._triggerParameter = triggerOptions.parameter;
  52669. }
  52670. else {
  52671. this.trigger = triggerOptions;
  52672. }
  52673. this._nextActiveAction = this;
  52674. this._condition = condition;
  52675. }
  52676. /**
  52677. * Internal only
  52678. * @hidden
  52679. */
  52680. Action.prototype._prepare = function () {
  52681. };
  52682. /**
  52683. * Gets the trigger parameters
  52684. * @returns the trigger parameters
  52685. */
  52686. Action.prototype.getTriggerParameter = function () {
  52687. return this._triggerParameter;
  52688. };
  52689. /**
  52690. * Internal only - executes current action event
  52691. * @hidden
  52692. */
  52693. Action.prototype._executeCurrent = function (evt) {
  52694. if (this._nextActiveAction._condition) {
  52695. var condition = this._nextActiveAction._condition;
  52696. var currentRenderId = this._actionManager.getScene().getRenderId();
  52697. // We cache the current evaluation for the current frame
  52698. if (condition._evaluationId === currentRenderId) {
  52699. if (!condition._currentResult) {
  52700. return;
  52701. }
  52702. }
  52703. else {
  52704. condition._evaluationId = currentRenderId;
  52705. if (!condition.isValid()) {
  52706. condition._currentResult = false;
  52707. return;
  52708. }
  52709. condition._currentResult = true;
  52710. }
  52711. }
  52712. this.onBeforeExecuteObservable.notifyObservers(this);
  52713. this._nextActiveAction.execute(evt);
  52714. this.skipToNextActiveAction();
  52715. };
  52716. /**
  52717. * Execute placeholder for child classes
  52718. * @param evt optional action event
  52719. */
  52720. Action.prototype.execute = function (evt) {
  52721. };
  52722. /**
  52723. * Skips to next active action
  52724. */
  52725. Action.prototype.skipToNextActiveAction = function () {
  52726. if (this._nextActiveAction._child) {
  52727. if (!this._nextActiveAction._child._actionManager) {
  52728. this._nextActiveAction._child._actionManager = this._actionManager;
  52729. }
  52730. this._nextActiveAction = this._nextActiveAction._child;
  52731. }
  52732. else {
  52733. this._nextActiveAction = this;
  52734. }
  52735. };
  52736. /**
  52737. * Adds action to chain of actions, may be a DoNothingAction
  52738. * @param action defines the next action to execute
  52739. * @returns The action passed in
  52740. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52741. */
  52742. Action.prototype.then = function (action) {
  52743. this._child = action;
  52744. action._actionManager = this._actionManager;
  52745. action._prepare();
  52746. return action;
  52747. };
  52748. /**
  52749. * Internal only
  52750. * @hidden
  52751. */
  52752. Action.prototype._getProperty = function (propertyPath) {
  52753. return this._actionManager._getProperty(propertyPath);
  52754. };
  52755. /**
  52756. * Internal only
  52757. * @hidden
  52758. */
  52759. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52760. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52761. };
  52762. /**
  52763. * Serialize placeholder for child classes
  52764. * @param parent of child
  52765. * @returns the serialized object
  52766. */
  52767. Action.prototype.serialize = function (parent) {
  52768. };
  52769. /**
  52770. * Internal only called by serialize
  52771. * @hidden
  52772. */
  52773. Action.prototype._serialize = function (serializedAction, parent) {
  52774. var serializationObject = {
  52775. type: 1,
  52776. children: [],
  52777. name: serializedAction.name,
  52778. properties: serializedAction.properties || []
  52779. };
  52780. // Serialize child
  52781. if (this._child) {
  52782. this._child.serialize(serializationObject);
  52783. }
  52784. // Check if "this" has a condition
  52785. if (this._condition) {
  52786. var serializedCondition = this._condition.serialize();
  52787. serializedCondition.children.push(serializationObject);
  52788. if (parent) {
  52789. parent.children.push(serializedCondition);
  52790. }
  52791. return serializedCondition;
  52792. }
  52793. if (parent) {
  52794. parent.children.push(serializationObject);
  52795. }
  52796. return serializationObject;
  52797. };
  52798. /**
  52799. * Internal only
  52800. * @hidden
  52801. */
  52802. Action._SerializeValueAsString = function (value) {
  52803. if (typeof value === "number") {
  52804. return value.toString();
  52805. }
  52806. if (typeof value === "boolean") {
  52807. return value ? "true" : "false";
  52808. }
  52809. if (value instanceof BABYLON.Vector2) {
  52810. return value.x + ", " + value.y;
  52811. }
  52812. if (value instanceof BABYLON.Vector3) {
  52813. return value.x + ", " + value.y + ", " + value.z;
  52814. }
  52815. if (value instanceof BABYLON.Color3) {
  52816. return value.r + ", " + value.g + ", " + value.b;
  52817. }
  52818. if (value instanceof BABYLON.Color4) {
  52819. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52820. }
  52821. return value; // string
  52822. };
  52823. /**
  52824. * Internal only
  52825. * @hidden
  52826. */
  52827. Action._GetTargetProperty = function (target) {
  52828. return {
  52829. name: "target",
  52830. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52831. : target instanceof BABYLON.Light ? "LightProperties"
  52832. : target instanceof BABYLON.Camera ? "CameraProperties"
  52833. : "SceneProperties",
  52834. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52835. };
  52836. };
  52837. return Action;
  52838. }());
  52839. BABYLON.Action = Action;
  52840. })(BABYLON || (BABYLON = {}));
  52841. //# sourceMappingURL=babylon.action.js.map
  52842. var BABYLON;
  52843. (function (BABYLON) {
  52844. /**
  52845. * ActionEvent is the event being sent when an action is triggered.
  52846. */
  52847. var ActionEvent = /** @class */ (function () {
  52848. /**
  52849. * Creates a new ActionEvent
  52850. * @param source The mesh or sprite that triggered the action
  52851. * @param pointerX The X mouse cursor position at the time of the event
  52852. * @param pointerY The Y mouse cursor position at the time of the event
  52853. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52854. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52855. * @param additionalData additional data for the event
  52856. */
  52857. function ActionEvent(
  52858. /** The mesh or sprite that triggered the action */
  52859. source,
  52860. /** The X mouse cursor position at the time of the event */
  52861. pointerX,
  52862. /** The Y mouse cursor position at the time of the event */
  52863. pointerY,
  52864. /** The mesh that is currently pointed at (can be null) */
  52865. meshUnderPointer,
  52866. /** the original (browser) event that triggered the ActionEvent */
  52867. sourceEvent,
  52868. /** additional data for the event */
  52869. additionalData) {
  52870. this.source = source;
  52871. this.pointerX = pointerX;
  52872. this.pointerY = pointerY;
  52873. this.meshUnderPointer = meshUnderPointer;
  52874. this.sourceEvent = sourceEvent;
  52875. this.additionalData = additionalData;
  52876. }
  52877. /**
  52878. * Helper function to auto-create an ActionEvent from a source mesh.
  52879. * @param source The source mesh that triggered the event
  52880. * @param evt The original (browser) event
  52881. * @param additionalData additional data for the event
  52882. * @returns the new ActionEvent
  52883. */
  52884. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52885. var scene = source.getScene();
  52886. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52887. };
  52888. /**
  52889. * Helper function to auto-create an ActionEvent from a source sprite
  52890. * @param source The source sprite that triggered the event
  52891. * @param scene Scene associated with the sprite
  52892. * @param evt The original (browser) event
  52893. * @param additionalData additional data for the event
  52894. * @returns the new ActionEvent
  52895. */
  52896. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52897. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52898. };
  52899. /**
  52900. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52901. * @param scene the scene where the event occurred
  52902. * @param evt The original (browser) event
  52903. * @returns the new ActionEvent
  52904. */
  52905. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52906. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52907. };
  52908. /**
  52909. * Helper function to auto-create an ActionEvent from a primitive
  52910. * @param prim defines the target primitive
  52911. * @param pointerPos defines the pointer position
  52912. * @param evt The original (browser) event
  52913. * @param additionalData additional data for the event
  52914. * @returns the new ActionEvent
  52915. */
  52916. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52917. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52918. };
  52919. return ActionEvent;
  52920. }());
  52921. BABYLON.ActionEvent = ActionEvent;
  52922. /**
  52923. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52924. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52925. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52926. */
  52927. var ActionManager = /** @class */ (function () {
  52928. /**
  52929. * Creates a new action manager
  52930. * @param scene defines the hosting scene
  52931. */
  52932. function ActionManager(scene) {
  52933. // Members
  52934. /** Gets the list of actions */
  52935. this.actions = new Array();
  52936. /** Gets the cursor to use when hovering items */
  52937. this.hoverCursor = '';
  52938. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52939. scene.actionManagers.push(this);
  52940. }
  52941. Object.defineProperty(ActionManager, "NothingTrigger", {
  52942. /**
  52943. * Nothing
  52944. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52945. */
  52946. get: function () {
  52947. return ActionManager._NothingTrigger;
  52948. },
  52949. enumerable: true,
  52950. configurable: true
  52951. });
  52952. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52953. /**
  52954. * On pick
  52955. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52956. */
  52957. get: function () {
  52958. return ActionManager._OnPickTrigger;
  52959. },
  52960. enumerable: true,
  52961. configurable: true
  52962. });
  52963. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52964. /**
  52965. * On left pick
  52966. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52967. */
  52968. get: function () {
  52969. return ActionManager._OnLeftPickTrigger;
  52970. },
  52971. enumerable: true,
  52972. configurable: true
  52973. });
  52974. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52975. /**
  52976. * On right pick
  52977. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52978. */
  52979. get: function () {
  52980. return ActionManager._OnRightPickTrigger;
  52981. },
  52982. enumerable: true,
  52983. configurable: true
  52984. });
  52985. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52986. /**
  52987. * On center pick
  52988. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52989. */
  52990. get: function () {
  52991. return ActionManager._OnCenterPickTrigger;
  52992. },
  52993. enumerable: true,
  52994. configurable: true
  52995. });
  52996. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52997. /**
  52998. * On pick down
  52999. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53000. */
  53001. get: function () {
  53002. return ActionManager._OnPickDownTrigger;
  53003. },
  53004. enumerable: true,
  53005. configurable: true
  53006. });
  53007. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53008. /**
  53009. * On double pick
  53010. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53011. */
  53012. get: function () {
  53013. return ActionManager._OnDoublePickTrigger;
  53014. },
  53015. enumerable: true,
  53016. configurable: true
  53017. });
  53018. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53019. /**
  53020. * On pick up
  53021. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53022. */
  53023. get: function () {
  53024. return ActionManager._OnPickUpTrigger;
  53025. },
  53026. enumerable: true,
  53027. configurable: true
  53028. });
  53029. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53030. /**
  53031. * On pick out.
  53032. * This trigger will only be raised if you also declared a OnPickDown
  53033. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53034. */
  53035. get: function () {
  53036. return ActionManager._OnPickOutTrigger;
  53037. },
  53038. enumerable: true,
  53039. configurable: true
  53040. });
  53041. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53042. /**
  53043. * On long press
  53044. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53045. */
  53046. get: function () {
  53047. return ActionManager._OnLongPressTrigger;
  53048. },
  53049. enumerable: true,
  53050. configurable: true
  53051. });
  53052. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53053. /**
  53054. * On pointer over
  53055. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53056. */
  53057. get: function () {
  53058. return ActionManager._OnPointerOverTrigger;
  53059. },
  53060. enumerable: true,
  53061. configurable: true
  53062. });
  53063. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53064. /**
  53065. * On pointer out
  53066. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53067. */
  53068. get: function () {
  53069. return ActionManager._OnPointerOutTrigger;
  53070. },
  53071. enumerable: true,
  53072. configurable: true
  53073. });
  53074. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53075. /**
  53076. * On every frame
  53077. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53078. */
  53079. get: function () {
  53080. return ActionManager._OnEveryFrameTrigger;
  53081. },
  53082. enumerable: true,
  53083. configurable: true
  53084. });
  53085. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53086. /**
  53087. * On intersection enter
  53088. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53089. */
  53090. get: function () {
  53091. return ActionManager._OnIntersectionEnterTrigger;
  53092. },
  53093. enumerable: true,
  53094. configurable: true
  53095. });
  53096. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53097. /**
  53098. * On intersection exit
  53099. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53100. */
  53101. get: function () {
  53102. return ActionManager._OnIntersectionExitTrigger;
  53103. },
  53104. enumerable: true,
  53105. configurable: true
  53106. });
  53107. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53108. /**
  53109. * On key down
  53110. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53111. */
  53112. get: function () {
  53113. return ActionManager._OnKeyDownTrigger;
  53114. },
  53115. enumerable: true,
  53116. configurable: true
  53117. });
  53118. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53119. /**
  53120. * On key up
  53121. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53122. */
  53123. get: function () {
  53124. return ActionManager._OnKeyUpTrigger;
  53125. },
  53126. enumerable: true,
  53127. configurable: true
  53128. });
  53129. // Methods
  53130. /**
  53131. * Releases all associated resources
  53132. */
  53133. ActionManager.prototype.dispose = function () {
  53134. var index = this._scene.actionManagers.indexOf(this);
  53135. for (var i = 0; i < this.actions.length; i++) {
  53136. var action = this.actions[i];
  53137. ActionManager.Triggers[action.trigger]--;
  53138. if (ActionManager.Triggers[action.trigger] === 0) {
  53139. delete ActionManager.Triggers[action.trigger];
  53140. }
  53141. }
  53142. if (index > -1) {
  53143. this._scene.actionManagers.splice(index, 1);
  53144. }
  53145. };
  53146. /**
  53147. * Gets hosting scene
  53148. * @returns the hosting scene
  53149. */
  53150. ActionManager.prototype.getScene = function () {
  53151. return this._scene;
  53152. };
  53153. /**
  53154. * Does this action manager handles actions of any of the given triggers
  53155. * @param triggers defines the triggers to be tested
  53156. * @return a boolean indicating whether one (or more) of the triggers is handled
  53157. */
  53158. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53159. for (var index = 0; index < this.actions.length; index++) {
  53160. var action = this.actions[index];
  53161. if (triggers.indexOf(action.trigger) > -1) {
  53162. return true;
  53163. }
  53164. }
  53165. return false;
  53166. };
  53167. /**
  53168. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53169. * speed.
  53170. * @param triggerA defines the trigger to be tested
  53171. * @param triggerB defines the trigger to be tested
  53172. * @return a boolean indicating whether one (or more) of the triggers is handled
  53173. */
  53174. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53175. for (var index = 0; index < this.actions.length; index++) {
  53176. var action = this.actions[index];
  53177. if (triggerA == action.trigger || triggerB == action.trigger) {
  53178. return true;
  53179. }
  53180. }
  53181. return false;
  53182. };
  53183. /**
  53184. * Does this action manager handles actions of a given trigger
  53185. * @param trigger defines the trigger to be tested
  53186. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53187. * @return whether the trigger is handled
  53188. */
  53189. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53190. for (var index = 0; index < this.actions.length; index++) {
  53191. var action = this.actions[index];
  53192. if (action.trigger === trigger) {
  53193. if (parameterPredicate) {
  53194. if (parameterPredicate(action.getTriggerParameter())) {
  53195. return true;
  53196. }
  53197. }
  53198. else {
  53199. return true;
  53200. }
  53201. }
  53202. }
  53203. return false;
  53204. };
  53205. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53206. /**
  53207. * Does this action manager has pointer triggers
  53208. */
  53209. get: function () {
  53210. for (var index = 0; index < this.actions.length; index++) {
  53211. var action = this.actions[index];
  53212. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53213. return true;
  53214. }
  53215. }
  53216. return false;
  53217. },
  53218. enumerable: true,
  53219. configurable: true
  53220. });
  53221. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53222. /**
  53223. * Does this action manager has pick triggers
  53224. */
  53225. get: function () {
  53226. for (var index = 0; index < this.actions.length; index++) {
  53227. var action = this.actions[index];
  53228. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53229. return true;
  53230. }
  53231. }
  53232. return false;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. Object.defineProperty(ActionManager, "HasTriggers", {
  53238. /**
  53239. * Does exist one action manager with at least one trigger
  53240. **/
  53241. get: function () {
  53242. for (var t in ActionManager.Triggers) {
  53243. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53244. return true;
  53245. }
  53246. }
  53247. return false;
  53248. },
  53249. enumerable: true,
  53250. configurable: true
  53251. });
  53252. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53253. /**
  53254. * Does exist one action manager with at least one pick trigger
  53255. **/
  53256. get: function () {
  53257. for (var t in ActionManager.Triggers) {
  53258. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53259. var t_int = parseInt(t);
  53260. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53261. return true;
  53262. }
  53263. }
  53264. }
  53265. return false;
  53266. },
  53267. enumerable: true,
  53268. configurable: true
  53269. });
  53270. /**
  53271. * Does exist one action manager that handles actions of a given trigger
  53272. * @param trigger defines the trigger to be tested
  53273. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53274. **/
  53275. ActionManager.HasSpecificTrigger = function (trigger) {
  53276. for (var t in ActionManager.Triggers) {
  53277. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53278. var t_int = parseInt(t);
  53279. if (t_int === trigger) {
  53280. return true;
  53281. }
  53282. }
  53283. }
  53284. return false;
  53285. };
  53286. /**
  53287. * Registers an action to this action manager
  53288. * @param action defines the action to be registered
  53289. * @return the action amended (prepared) after registration
  53290. */
  53291. ActionManager.prototype.registerAction = function (action) {
  53292. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53293. if (this.getScene().actionManager !== this) {
  53294. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53295. return null;
  53296. }
  53297. }
  53298. this.actions.push(action);
  53299. if (ActionManager.Triggers[action.trigger]) {
  53300. ActionManager.Triggers[action.trigger]++;
  53301. }
  53302. else {
  53303. ActionManager.Triggers[action.trigger] = 1;
  53304. }
  53305. action._actionManager = this;
  53306. action._prepare();
  53307. return action;
  53308. };
  53309. /**
  53310. * Unregisters an action to this action manager
  53311. * @param action defines the action to be unregistered
  53312. * @return a boolean indicating whether the action has been unregistered
  53313. */
  53314. ActionManager.prototype.unregisterAction = function (action) {
  53315. var index = this.actions.indexOf(action);
  53316. if (index !== -1) {
  53317. this.actions.splice(index, 1);
  53318. ActionManager.Triggers[action.trigger] -= 1;
  53319. if (ActionManager.Triggers[action.trigger] === 0) {
  53320. delete ActionManager.Triggers[action.trigger];
  53321. }
  53322. delete action._actionManager;
  53323. return true;
  53324. }
  53325. return false;
  53326. };
  53327. /**
  53328. * Process a specific trigger
  53329. * @param trigger defines the trigger to process
  53330. * @param evt defines the event details to be processed
  53331. */
  53332. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53333. for (var index = 0; index < this.actions.length; index++) {
  53334. var action = this.actions[index];
  53335. if (action.trigger === trigger) {
  53336. if (evt) {
  53337. if (trigger === ActionManager.OnKeyUpTrigger
  53338. || trigger === ActionManager.OnKeyDownTrigger) {
  53339. var parameter = action.getTriggerParameter();
  53340. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53341. if (!parameter.toLowerCase) {
  53342. continue;
  53343. }
  53344. var lowerCase = parameter.toLowerCase();
  53345. if (lowerCase !== evt.sourceEvent.key) {
  53346. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53347. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53348. if (actualkey !== lowerCase) {
  53349. continue;
  53350. }
  53351. }
  53352. }
  53353. }
  53354. }
  53355. action._executeCurrent(evt);
  53356. }
  53357. }
  53358. };
  53359. /** @hidden */
  53360. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53361. var properties = propertyPath.split(".");
  53362. for (var index = 0; index < properties.length - 1; index++) {
  53363. target = target[properties[index]];
  53364. }
  53365. return target;
  53366. };
  53367. /** @hidden */
  53368. ActionManager.prototype._getProperty = function (propertyPath) {
  53369. var properties = propertyPath.split(".");
  53370. return properties[properties.length - 1];
  53371. };
  53372. /**
  53373. * Serialize this manager to a JSON object
  53374. * @param name defines the property name to store this manager
  53375. * @returns a JSON representation of this manager
  53376. */
  53377. ActionManager.prototype.serialize = function (name) {
  53378. var root = {
  53379. children: new Array(),
  53380. name: name,
  53381. type: 3,
  53382. properties: new Array() // Empty for root but required
  53383. };
  53384. for (var i = 0; i < this.actions.length; i++) {
  53385. var triggerObject = {
  53386. type: 0,
  53387. children: new Array(),
  53388. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53389. properties: new Array()
  53390. };
  53391. var triggerOptions = this.actions[i].triggerOptions;
  53392. if (triggerOptions && typeof triggerOptions !== "number") {
  53393. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53394. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53395. }
  53396. else {
  53397. var parameter = {};
  53398. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53399. if (triggerOptions.parameter.mesh) {
  53400. parameter._meshId = triggerOptions.parameter.mesh.id;
  53401. }
  53402. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53403. }
  53404. }
  53405. // Serialize child action, recursively
  53406. this.actions[i].serialize(triggerObject);
  53407. // Add serialized trigger
  53408. root.children.push(triggerObject);
  53409. }
  53410. return root;
  53411. };
  53412. /**
  53413. * Creates a new ActionManager from a JSON data
  53414. * @param parsedActions defines the JSON data to read from
  53415. * @param object defines the hosting mesh
  53416. * @param scene defines the hosting scene
  53417. */
  53418. ActionManager.Parse = function (parsedActions, object, scene) {
  53419. var actionManager = new ActionManager(scene);
  53420. if (object === null)
  53421. scene.actionManager = actionManager;
  53422. else
  53423. object.actionManager = actionManager;
  53424. // instanciate a new object
  53425. var instanciate = function (name, params) {
  53426. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53427. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53428. newInstance.constructor.apply(newInstance, params);
  53429. return newInstance;
  53430. };
  53431. var parseParameter = function (name, value, target, propertyPath) {
  53432. if (propertyPath === null) {
  53433. // String, boolean or float
  53434. var floatValue = parseFloat(value);
  53435. if (value === "true" || value === "false")
  53436. return value === "true";
  53437. else
  53438. return isNaN(floatValue) ? value : floatValue;
  53439. }
  53440. var effectiveTarget = propertyPath.split(".");
  53441. var values = value.split(",");
  53442. // Get effective Target
  53443. for (var i = 0; i < effectiveTarget.length; i++) {
  53444. target = target[effectiveTarget[i]];
  53445. }
  53446. // Return appropriate value with its type
  53447. if (typeof (target) === "boolean")
  53448. return values[0] === "true";
  53449. if (typeof (target) === "string")
  53450. return values[0];
  53451. // Parameters with multiple values such as Vector3 etc.
  53452. var split = new Array();
  53453. for (var i = 0; i < values.length; i++)
  53454. split.push(parseFloat(values[i]));
  53455. if (target instanceof BABYLON.Vector3)
  53456. return BABYLON.Vector3.FromArray(split);
  53457. if (target instanceof BABYLON.Vector4)
  53458. return BABYLON.Vector4.FromArray(split);
  53459. if (target instanceof BABYLON.Color3)
  53460. return BABYLON.Color3.FromArray(split);
  53461. if (target instanceof BABYLON.Color4)
  53462. return BABYLON.Color4.FromArray(split);
  53463. return parseFloat(values[0]);
  53464. };
  53465. // traverse graph per trigger
  53466. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53467. if (combineArray === void 0) { combineArray = null; }
  53468. if (parsedAction.detached)
  53469. return;
  53470. var parameters = new Array();
  53471. var target = null;
  53472. var propertyPath = null;
  53473. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53474. // Parameters
  53475. if (parsedAction.type === 2)
  53476. parameters.push(actionManager);
  53477. else
  53478. parameters.push(trigger);
  53479. if (combine) {
  53480. var actions = new Array();
  53481. for (var j = 0; j < parsedAction.combine.length; j++) {
  53482. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53483. }
  53484. parameters.push(actions);
  53485. }
  53486. else {
  53487. for (var i = 0; i < parsedAction.properties.length; i++) {
  53488. var value = parsedAction.properties[i].value;
  53489. var name = parsedAction.properties[i].name;
  53490. var targetType = parsedAction.properties[i].targetType;
  53491. if (name === "target")
  53492. if (targetType !== null && targetType === "SceneProperties")
  53493. value = target = scene;
  53494. else
  53495. value = target = scene.getNodeByName(value);
  53496. else if (name === "parent")
  53497. value = scene.getNodeByName(value);
  53498. else if (name === "sound")
  53499. value = scene.getSoundByName(value);
  53500. else if (name !== "propertyPath") {
  53501. if (parsedAction.type === 2 && name === "operator")
  53502. value = BABYLON.ValueCondition[value];
  53503. else
  53504. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53505. }
  53506. else {
  53507. propertyPath = value;
  53508. }
  53509. parameters.push(value);
  53510. }
  53511. }
  53512. if (combineArray === null) {
  53513. parameters.push(condition);
  53514. }
  53515. else {
  53516. parameters.push(null);
  53517. }
  53518. // If interpolate value action
  53519. if (parsedAction.name === "InterpolateValueAction") {
  53520. var param = parameters[parameters.length - 2];
  53521. parameters[parameters.length - 1] = param;
  53522. parameters[parameters.length - 2] = condition;
  53523. }
  53524. // Action or condition(s) and not CombineAction
  53525. var newAction = instanciate(parsedAction.name, parameters);
  53526. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53527. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53528. if (action)
  53529. action.then(nothing);
  53530. else
  53531. actionManager.registerAction(nothing);
  53532. action = nothing;
  53533. }
  53534. if (combineArray === null) {
  53535. if (newAction instanceof BABYLON.Condition) {
  53536. condition = newAction;
  53537. newAction = action;
  53538. }
  53539. else {
  53540. condition = null;
  53541. if (action)
  53542. action.then(newAction);
  53543. else
  53544. actionManager.registerAction(newAction);
  53545. }
  53546. }
  53547. else {
  53548. combineArray.push(newAction);
  53549. }
  53550. for (var i = 0; i < parsedAction.children.length; i++)
  53551. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53552. };
  53553. // triggers
  53554. for (var i = 0; i < parsedActions.children.length; i++) {
  53555. var triggerParams;
  53556. var trigger = parsedActions.children[i];
  53557. if (trigger.properties.length > 0) {
  53558. var param = trigger.properties[0].value;
  53559. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53560. if (value._meshId) {
  53561. value.mesh = scene.getMeshByID(value._meshId);
  53562. }
  53563. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53564. }
  53565. else
  53566. triggerParams = ActionManager[trigger.name];
  53567. for (var j = 0; j < trigger.children.length; j++) {
  53568. if (!trigger.detached)
  53569. traverse(trigger.children[j], triggerParams, null, null);
  53570. }
  53571. }
  53572. };
  53573. /**
  53574. * Get a trigger name by index
  53575. * @param trigger defines the trigger index
  53576. * @returns a trigger name
  53577. */
  53578. ActionManager.GetTriggerName = function (trigger) {
  53579. switch (trigger) {
  53580. case 0: return "NothingTrigger";
  53581. case 1: return "OnPickTrigger";
  53582. case 2: return "OnLeftPickTrigger";
  53583. case 3: return "OnRightPickTrigger";
  53584. case 4: return "OnCenterPickTrigger";
  53585. case 5: return "OnPickDownTrigger";
  53586. case 6: return "OnPickUpTrigger";
  53587. case 7: return "OnLongPressTrigger";
  53588. case 8: return "OnPointerOverTrigger";
  53589. case 9: return "OnPointerOutTrigger";
  53590. case 10: return "OnEveryFrameTrigger";
  53591. case 11: return "OnIntersectionEnterTrigger";
  53592. case 12: return "OnIntersectionExitTrigger";
  53593. case 13: return "OnKeyDownTrigger";
  53594. case 14: return "OnKeyUpTrigger";
  53595. case 15: return "OnPickOutTrigger";
  53596. default: return "";
  53597. }
  53598. };
  53599. // Statics
  53600. ActionManager._NothingTrigger = 0;
  53601. ActionManager._OnPickTrigger = 1;
  53602. ActionManager._OnLeftPickTrigger = 2;
  53603. ActionManager._OnRightPickTrigger = 3;
  53604. ActionManager._OnCenterPickTrigger = 4;
  53605. ActionManager._OnPickDownTrigger = 5;
  53606. ActionManager._OnDoublePickTrigger = 6;
  53607. ActionManager._OnPickUpTrigger = 7;
  53608. ActionManager._OnLongPressTrigger = 8;
  53609. ActionManager._OnPointerOverTrigger = 9;
  53610. ActionManager._OnPointerOutTrigger = 10;
  53611. ActionManager._OnEveryFrameTrigger = 11;
  53612. ActionManager._OnIntersectionEnterTrigger = 12;
  53613. ActionManager._OnIntersectionExitTrigger = 13;
  53614. ActionManager._OnKeyDownTrigger = 14;
  53615. ActionManager._OnKeyUpTrigger = 15;
  53616. ActionManager._OnPickOutTrigger = 16;
  53617. /** Gets the list of active triggers */
  53618. ActionManager.Triggers = {};
  53619. return ActionManager;
  53620. }());
  53621. BABYLON.ActionManager = ActionManager;
  53622. })(BABYLON || (BABYLON = {}));
  53623. //# sourceMappingURL=babylon.actionManager.js.map
  53624. var BABYLON;
  53625. (function (BABYLON) {
  53626. var InterpolateValueAction = /** @class */ (function (_super) {
  53627. __extends(InterpolateValueAction, _super);
  53628. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53629. if (duration === void 0) { duration = 1000; }
  53630. var _this = _super.call(this, triggerOptions, condition) || this;
  53631. _this.propertyPath = propertyPath;
  53632. _this.value = value;
  53633. _this.duration = duration;
  53634. _this.stopOtherAnimations = stopOtherAnimations;
  53635. _this.onInterpolationDone = onInterpolationDone;
  53636. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53637. _this._target = _this._effectiveTarget = target;
  53638. return _this;
  53639. }
  53640. /** @hidden */
  53641. InterpolateValueAction.prototype._prepare = function () {
  53642. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53643. this._property = this._getProperty(this.propertyPath);
  53644. };
  53645. InterpolateValueAction.prototype.execute = function () {
  53646. var _this = this;
  53647. var scene = this._actionManager.getScene();
  53648. var keys = [
  53649. {
  53650. frame: 0,
  53651. value: this._effectiveTarget[this._property]
  53652. }, {
  53653. frame: 100,
  53654. value: this.value
  53655. }
  53656. ];
  53657. var dataType;
  53658. if (typeof this.value === "number") {
  53659. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53660. }
  53661. else if (this.value instanceof BABYLON.Color3) {
  53662. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53663. }
  53664. else if (this.value instanceof BABYLON.Vector3) {
  53665. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53666. }
  53667. else if (this.value instanceof BABYLON.Matrix) {
  53668. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53669. }
  53670. else if (this.value instanceof BABYLON.Quaternion) {
  53671. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53672. }
  53673. else {
  53674. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53675. return;
  53676. }
  53677. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53678. animation.setKeys(keys);
  53679. if (this.stopOtherAnimations) {
  53680. scene.stopAnimation(this._effectiveTarget);
  53681. }
  53682. var wrapper = function () {
  53683. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53684. if (_this.onInterpolationDone) {
  53685. _this.onInterpolationDone();
  53686. }
  53687. };
  53688. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53689. };
  53690. InterpolateValueAction.prototype.serialize = function (parent) {
  53691. return _super.prototype._serialize.call(this, {
  53692. name: "InterpolateValueAction",
  53693. properties: [
  53694. BABYLON.Action._GetTargetProperty(this._target),
  53695. { name: "propertyPath", value: this.propertyPath },
  53696. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53697. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53698. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53699. ]
  53700. }, parent);
  53701. };
  53702. return InterpolateValueAction;
  53703. }(BABYLON.Action));
  53704. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53705. })(BABYLON || (BABYLON = {}));
  53706. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53707. var BABYLON;
  53708. (function (BABYLON) {
  53709. var SwitchBooleanAction = /** @class */ (function (_super) {
  53710. __extends(SwitchBooleanAction, _super);
  53711. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53712. var _this = _super.call(this, triggerOptions, condition) || this;
  53713. _this.propertyPath = propertyPath;
  53714. _this._target = _this._effectiveTarget = target;
  53715. return _this;
  53716. }
  53717. /** @hidden */
  53718. SwitchBooleanAction.prototype._prepare = function () {
  53719. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53720. this._property = this._getProperty(this.propertyPath);
  53721. };
  53722. SwitchBooleanAction.prototype.execute = function () {
  53723. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53724. };
  53725. SwitchBooleanAction.prototype.serialize = function (parent) {
  53726. return _super.prototype._serialize.call(this, {
  53727. name: "SwitchBooleanAction",
  53728. properties: [
  53729. BABYLON.Action._GetTargetProperty(this._target),
  53730. { name: "propertyPath", value: this.propertyPath }
  53731. ]
  53732. }, parent);
  53733. };
  53734. return SwitchBooleanAction;
  53735. }(BABYLON.Action));
  53736. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53737. var SetStateAction = /** @class */ (function (_super) {
  53738. __extends(SetStateAction, _super);
  53739. function SetStateAction(triggerOptions, target, value, condition) {
  53740. var _this = _super.call(this, triggerOptions, condition) || this;
  53741. _this.value = value;
  53742. _this._target = target;
  53743. return _this;
  53744. }
  53745. SetStateAction.prototype.execute = function () {
  53746. this._target.state = this.value;
  53747. };
  53748. SetStateAction.prototype.serialize = function (parent) {
  53749. return _super.prototype._serialize.call(this, {
  53750. name: "SetStateAction",
  53751. properties: [
  53752. BABYLON.Action._GetTargetProperty(this._target),
  53753. { name: "value", value: this.value }
  53754. ]
  53755. }, parent);
  53756. };
  53757. return SetStateAction;
  53758. }(BABYLON.Action));
  53759. BABYLON.SetStateAction = SetStateAction;
  53760. var SetValueAction = /** @class */ (function (_super) {
  53761. __extends(SetValueAction, _super);
  53762. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53763. var _this = _super.call(this, triggerOptions, condition) || this;
  53764. _this.propertyPath = propertyPath;
  53765. _this.value = value;
  53766. _this._target = _this._effectiveTarget = target;
  53767. return _this;
  53768. }
  53769. /** @hidden */
  53770. SetValueAction.prototype._prepare = function () {
  53771. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53772. this._property = this._getProperty(this.propertyPath);
  53773. };
  53774. SetValueAction.prototype.execute = function () {
  53775. this._effectiveTarget[this._property] = this.value;
  53776. if (this._target.markAsDirty) {
  53777. this._target.markAsDirty(this._property);
  53778. }
  53779. };
  53780. SetValueAction.prototype.serialize = function (parent) {
  53781. return _super.prototype._serialize.call(this, {
  53782. name: "SetValueAction",
  53783. properties: [
  53784. BABYLON.Action._GetTargetProperty(this._target),
  53785. { name: "propertyPath", value: this.propertyPath },
  53786. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53787. ]
  53788. }, parent);
  53789. };
  53790. return SetValueAction;
  53791. }(BABYLON.Action));
  53792. BABYLON.SetValueAction = SetValueAction;
  53793. var IncrementValueAction = /** @class */ (function (_super) {
  53794. __extends(IncrementValueAction, _super);
  53795. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53796. var _this = _super.call(this, triggerOptions, condition) || this;
  53797. _this.propertyPath = propertyPath;
  53798. _this.value = value;
  53799. _this._target = _this._effectiveTarget = target;
  53800. return _this;
  53801. }
  53802. /** @hidden */
  53803. IncrementValueAction.prototype._prepare = function () {
  53804. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53805. this._property = this._getProperty(this.propertyPath);
  53806. if (typeof this._effectiveTarget[this._property] !== "number") {
  53807. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53808. }
  53809. };
  53810. IncrementValueAction.prototype.execute = function () {
  53811. this._effectiveTarget[this._property] += this.value;
  53812. if (this._target.markAsDirty) {
  53813. this._target.markAsDirty(this._property);
  53814. }
  53815. };
  53816. IncrementValueAction.prototype.serialize = function (parent) {
  53817. return _super.prototype._serialize.call(this, {
  53818. name: "IncrementValueAction",
  53819. properties: [
  53820. BABYLON.Action._GetTargetProperty(this._target),
  53821. { name: "propertyPath", value: this.propertyPath },
  53822. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53823. ]
  53824. }, parent);
  53825. };
  53826. return IncrementValueAction;
  53827. }(BABYLON.Action));
  53828. BABYLON.IncrementValueAction = IncrementValueAction;
  53829. var PlayAnimationAction = /** @class */ (function (_super) {
  53830. __extends(PlayAnimationAction, _super);
  53831. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53832. var _this = _super.call(this, triggerOptions, condition) || this;
  53833. _this.from = from;
  53834. _this.to = to;
  53835. _this.loop = loop;
  53836. _this._target = target;
  53837. return _this;
  53838. }
  53839. /** @hidden */
  53840. PlayAnimationAction.prototype._prepare = function () {
  53841. };
  53842. PlayAnimationAction.prototype.execute = function () {
  53843. var scene = this._actionManager.getScene();
  53844. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53845. };
  53846. PlayAnimationAction.prototype.serialize = function (parent) {
  53847. return _super.prototype._serialize.call(this, {
  53848. name: "PlayAnimationAction",
  53849. properties: [
  53850. BABYLON.Action._GetTargetProperty(this._target),
  53851. { name: "from", value: String(this.from) },
  53852. { name: "to", value: String(this.to) },
  53853. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53854. ]
  53855. }, parent);
  53856. };
  53857. return PlayAnimationAction;
  53858. }(BABYLON.Action));
  53859. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53860. var StopAnimationAction = /** @class */ (function (_super) {
  53861. __extends(StopAnimationAction, _super);
  53862. function StopAnimationAction(triggerOptions, target, condition) {
  53863. var _this = _super.call(this, triggerOptions, condition) || this;
  53864. _this._target = target;
  53865. return _this;
  53866. }
  53867. /** @hidden */
  53868. StopAnimationAction.prototype._prepare = function () {
  53869. };
  53870. StopAnimationAction.prototype.execute = function () {
  53871. var scene = this._actionManager.getScene();
  53872. scene.stopAnimation(this._target);
  53873. };
  53874. StopAnimationAction.prototype.serialize = function (parent) {
  53875. return _super.prototype._serialize.call(this, {
  53876. name: "StopAnimationAction",
  53877. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53878. }, parent);
  53879. };
  53880. return StopAnimationAction;
  53881. }(BABYLON.Action));
  53882. BABYLON.StopAnimationAction = StopAnimationAction;
  53883. var DoNothingAction = /** @class */ (function (_super) {
  53884. __extends(DoNothingAction, _super);
  53885. function DoNothingAction(triggerOptions, condition) {
  53886. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53887. return _super.call(this, triggerOptions, condition) || this;
  53888. }
  53889. DoNothingAction.prototype.execute = function () {
  53890. };
  53891. DoNothingAction.prototype.serialize = function (parent) {
  53892. return _super.prototype._serialize.call(this, {
  53893. name: "DoNothingAction",
  53894. properties: []
  53895. }, parent);
  53896. };
  53897. return DoNothingAction;
  53898. }(BABYLON.Action));
  53899. BABYLON.DoNothingAction = DoNothingAction;
  53900. var CombineAction = /** @class */ (function (_super) {
  53901. __extends(CombineAction, _super);
  53902. function CombineAction(triggerOptions, children, condition) {
  53903. var _this = _super.call(this, triggerOptions, condition) || this;
  53904. _this.children = children;
  53905. return _this;
  53906. }
  53907. /** @hidden */
  53908. CombineAction.prototype._prepare = function () {
  53909. for (var index = 0; index < this.children.length; index++) {
  53910. this.children[index]._actionManager = this._actionManager;
  53911. this.children[index]._prepare();
  53912. }
  53913. };
  53914. CombineAction.prototype.execute = function (evt) {
  53915. for (var index = 0; index < this.children.length; index++) {
  53916. this.children[index].execute(evt);
  53917. }
  53918. };
  53919. CombineAction.prototype.serialize = function (parent) {
  53920. var serializationObject = _super.prototype._serialize.call(this, {
  53921. name: "CombineAction",
  53922. properties: [],
  53923. combine: []
  53924. }, parent);
  53925. for (var i = 0; i < this.children.length; i++) {
  53926. serializationObject.combine.push(this.children[i].serialize(null));
  53927. }
  53928. return serializationObject;
  53929. };
  53930. return CombineAction;
  53931. }(BABYLON.Action));
  53932. BABYLON.CombineAction = CombineAction;
  53933. var ExecuteCodeAction = /** @class */ (function (_super) {
  53934. __extends(ExecuteCodeAction, _super);
  53935. function ExecuteCodeAction(triggerOptions, func, condition) {
  53936. var _this = _super.call(this, triggerOptions, condition) || this;
  53937. _this.func = func;
  53938. return _this;
  53939. }
  53940. ExecuteCodeAction.prototype.execute = function (evt) {
  53941. this.func(evt);
  53942. };
  53943. return ExecuteCodeAction;
  53944. }(BABYLON.Action));
  53945. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53946. var SetParentAction = /** @class */ (function (_super) {
  53947. __extends(SetParentAction, _super);
  53948. function SetParentAction(triggerOptions, target, parent, condition) {
  53949. var _this = _super.call(this, triggerOptions, condition) || this;
  53950. _this._target = target;
  53951. _this._parent = parent;
  53952. return _this;
  53953. }
  53954. /** @hidden */
  53955. SetParentAction.prototype._prepare = function () {
  53956. };
  53957. SetParentAction.prototype.execute = function () {
  53958. if (this._target.parent === this._parent) {
  53959. return;
  53960. }
  53961. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53962. invertParentWorldMatrix.invert();
  53963. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53964. this._target.parent = this._parent;
  53965. };
  53966. SetParentAction.prototype.serialize = function (parent) {
  53967. return _super.prototype._serialize.call(this, {
  53968. name: "SetParentAction",
  53969. properties: [
  53970. BABYLON.Action._GetTargetProperty(this._target),
  53971. BABYLON.Action._GetTargetProperty(this._parent),
  53972. ]
  53973. }, parent);
  53974. };
  53975. return SetParentAction;
  53976. }(BABYLON.Action));
  53977. BABYLON.SetParentAction = SetParentAction;
  53978. var PlaySoundAction = /** @class */ (function (_super) {
  53979. __extends(PlaySoundAction, _super);
  53980. function PlaySoundAction(triggerOptions, sound, condition) {
  53981. var _this = _super.call(this, triggerOptions, condition) || this;
  53982. _this._sound = sound;
  53983. return _this;
  53984. }
  53985. /** @hidden */
  53986. PlaySoundAction.prototype._prepare = function () {
  53987. };
  53988. PlaySoundAction.prototype.execute = function () {
  53989. if (this._sound !== undefined)
  53990. this._sound.play();
  53991. };
  53992. PlaySoundAction.prototype.serialize = function (parent) {
  53993. return _super.prototype._serialize.call(this, {
  53994. name: "PlaySoundAction",
  53995. properties: [{ name: "sound", value: this._sound.name }]
  53996. }, parent);
  53997. };
  53998. return PlaySoundAction;
  53999. }(BABYLON.Action));
  54000. BABYLON.PlaySoundAction = PlaySoundAction;
  54001. var StopSoundAction = /** @class */ (function (_super) {
  54002. __extends(StopSoundAction, _super);
  54003. function StopSoundAction(triggerOptions, sound, condition) {
  54004. var _this = _super.call(this, triggerOptions, condition) || this;
  54005. _this._sound = sound;
  54006. return _this;
  54007. }
  54008. /** @hidden */
  54009. StopSoundAction.prototype._prepare = function () {
  54010. };
  54011. StopSoundAction.prototype.execute = function () {
  54012. if (this._sound !== undefined)
  54013. this._sound.stop();
  54014. };
  54015. StopSoundAction.prototype.serialize = function (parent) {
  54016. return _super.prototype._serialize.call(this, {
  54017. name: "StopSoundAction",
  54018. properties: [{ name: "sound", value: this._sound.name }]
  54019. }, parent);
  54020. };
  54021. return StopSoundAction;
  54022. }(BABYLON.Action));
  54023. BABYLON.StopSoundAction = StopSoundAction;
  54024. })(BABYLON || (BABYLON = {}));
  54025. //# sourceMappingURL=babylon.directActions.js.map
  54026. var BABYLON;
  54027. (function (BABYLON) {
  54028. var SpriteManager = /** @class */ (function () {
  54029. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54030. if (epsilon === void 0) { epsilon = 0.01; }
  54031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54032. this.name = name;
  54033. this.sprites = new Array();
  54034. this.renderingGroupId = 0;
  54035. this.layerMask = 0x0FFFFFFF;
  54036. this.fogEnabled = true;
  54037. this.isPickable = false;
  54038. /**
  54039. * An event triggered when the manager is disposed.
  54040. */
  54041. this.onDisposeObservable = new BABYLON.Observable();
  54042. this._vertexBuffers = {};
  54043. this._capacity = capacity;
  54044. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54045. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54046. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54047. if (cellSize.width && cellSize.height) {
  54048. this.cellWidth = cellSize.width;
  54049. this.cellHeight = cellSize.height;
  54050. }
  54051. else if (cellSize !== undefined) {
  54052. this.cellWidth = cellSize;
  54053. this.cellHeight = cellSize;
  54054. }
  54055. else {
  54056. return;
  54057. }
  54058. this._epsilon = epsilon;
  54059. this._scene = scene;
  54060. this._scene.spriteManagers.push(this);
  54061. var indices = [];
  54062. var index = 0;
  54063. for (var count = 0; count < capacity; count++) {
  54064. indices.push(index);
  54065. indices.push(index + 1);
  54066. indices.push(index + 2);
  54067. indices.push(index);
  54068. indices.push(index + 2);
  54069. indices.push(index + 3);
  54070. index += 4;
  54071. }
  54072. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54073. // VBO
  54074. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54075. this._vertexData = new Float32Array(capacity * 16 * 4);
  54076. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54077. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54078. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54079. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54080. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54081. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54082. this._vertexBuffers["options"] = options;
  54083. this._vertexBuffers["cellInfo"] = cellInfo;
  54084. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54085. // Effects
  54086. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54087. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54088. }
  54089. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54090. set: function (callback) {
  54091. if (this._onDisposeObserver) {
  54092. this.onDisposeObservable.remove(this._onDisposeObserver);
  54093. }
  54094. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54095. },
  54096. enumerable: true,
  54097. configurable: true
  54098. });
  54099. Object.defineProperty(SpriteManager.prototype, "texture", {
  54100. get: function () {
  54101. return this._spriteTexture;
  54102. },
  54103. set: function (value) {
  54104. this._spriteTexture = value;
  54105. },
  54106. enumerable: true,
  54107. configurable: true
  54108. });
  54109. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54110. var arrayOffset = index * 16;
  54111. if (offsetX === 0)
  54112. offsetX = this._epsilon;
  54113. else if (offsetX === 1)
  54114. offsetX = 1 - this._epsilon;
  54115. if (offsetY === 0)
  54116. offsetY = this._epsilon;
  54117. else if (offsetY === 1)
  54118. offsetY = 1 - this._epsilon;
  54119. this._vertexData[arrayOffset] = sprite.position.x;
  54120. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54121. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54122. this._vertexData[arrayOffset + 3] = sprite.angle;
  54123. this._vertexData[arrayOffset + 4] = sprite.width;
  54124. this._vertexData[arrayOffset + 5] = sprite.height;
  54125. this._vertexData[arrayOffset + 6] = offsetX;
  54126. this._vertexData[arrayOffset + 7] = offsetY;
  54127. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54128. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54129. var offset = (sprite.cellIndex / rowSize) >> 0;
  54130. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54131. this._vertexData[arrayOffset + 11] = offset;
  54132. // Color
  54133. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54134. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54135. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54136. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54137. };
  54138. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54139. var count = Math.min(this._capacity, this.sprites.length);
  54140. var min = BABYLON.Vector3.Zero();
  54141. var max = BABYLON.Vector3.Zero();
  54142. var distance = Number.MAX_VALUE;
  54143. var currentSprite = null;
  54144. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54145. var cameraView = camera.getViewMatrix();
  54146. for (var index = 0; index < count; index++) {
  54147. var sprite = this.sprites[index];
  54148. if (!sprite) {
  54149. continue;
  54150. }
  54151. if (predicate) {
  54152. if (!predicate(sprite)) {
  54153. continue;
  54154. }
  54155. }
  54156. else if (!sprite.isPickable) {
  54157. continue;
  54158. }
  54159. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54160. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54161. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54162. if (ray.intersectsBoxMinMax(min, max)) {
  54163. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54164. if (distance > currentDistance) {
  54165. distance = currentDistance;
  54166. currentSprite = sprite;
  54167. if (fastCheck) {
  54168. break;
  54169. }
  54170. }
  54171. }
  54172. }
  54173. if (currentSprite) {
  54174. var result = new BABYLON.PickingInfo();
  54175. result.hit = true;
  54176. result.pickedSprite = currentSprite;
  54177. result.distance = distance;
  54178. return result;
  54179. }
  54180. return null;
  54181. };
  54182. SpriteManager.prototype.render = function () {
  54183. // Check
  54184. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54185. return;
  54186. var engine = this._scene.getEngine();
  54187. var baseSize = this._spriteTexture.getBaseSize();
  54188. // Sprites
  54189. var deltaTime = engine.getDeltaTime();
  54190. var max = Math.min(this._capacity, this.sprites.length);
  54191. var rowSize = baseSize.width / this.cellWidth;
  54192. var offset = 0;
  54193. for (var index = 0; index < max; index++) {
  54194. var sprite = this.sprites[index];
  54195. if (!sprite || !sprite.isVisible) {
  54196. continue;
  54197. }
  54198. sprite._animate(deltaTime);
  54199. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54200. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54201. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54202. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54203. }
  54204. this._buffer.update(this._vertexData);
  54205. // Render
  54206. var effect = this._effectBase;
  54207. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54208. effect = this._effectFog;
  54209. }
  54210. engine.enableEffect(effect);
  54211. var viewMatrix = this._scene.getViewMatrix();
  54212. effect.setTexture("diffuseSampler", this._spriteTexture);
  54213. effect.setMatrix("view", viewMatrix);
  54214. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54215. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54216. // Fog
  54217. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54218. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54219. effect.setColor3("vFogColor", this._scene.fogColor);
  54220. }
  54221. // VBOs
  54222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54223. // Draw order
  54224. engine.setDepthFunctionToLessOrEqual();
  54225. effect.setBool("alphaTest", true);
  54226. engine.setColorWrite(false);
  54227. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54228. engine.setColorWrite(true);
  54229. effect.setBool("alphaTest", false);
  54230. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54231. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54232. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54233. };
  54234. SpriteManager.prototype.dispose = function () {
  54235. if (this._buffer) {
  54236. this._buffer.dispose();
  54237. this._buffer = null;
  54238. }
  54239. if (this._indexBuffer) {
  54240. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54241. this._indexBuffer = null;
  54242. }
  54243. if (this._spriteTexture) {
  54244. this._spriteTexture.dispose();
  54245. this._spriteTexture = null;
  54246. }
  54247. // Remove from scene
  54248. var index = this._scene.spriteManagers.indexOf(this);
  54249. this._scene.spriteManagers.splice(index, 1);
  54250. // Callback
  54251. this.onDisposeObservable.notifyObservers(this);
  54252. this.onDisposeObservable.clear();
  54253. };
  54254. return SpriteManager;
  54255. }());
  54256. BABYLON.SpriteManager = SpriteManager;
  54257. })(BABYLON || (BABYLON = {}));
  54258. //# sourceMappingURL=babylon.spriteManager.js.map
  54259. var BABYLON;
  54260. (function (BABYLON) {
  54261. var Sprite = /** @class */ (function () {
  54262. function Sprite(name, manager) {
  54263. this.name = name;
  54264. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54265. this.width = 1.0;
  54266. this.height = 1.0;
  54267. this.angle = 0;
  54268. this.cellIndex = 0;
  54269. this.invertU = 0;
  54270. this.invertV = 0;
  54271. this.animations = new Array();
  54272. this.isPickable = false;
  54273. this._animationStarted = false;
  54274. this._loopAnimation = false;
  54275. this._fromIndex = 0;
  54276. this._toIndex = 0;
  54277. this._delay = 0;
  54278. this._direction = 1;
  54279. this._time = 0;
  54280. /**
  54281. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54282. */
  54283. this.isVisible = true;
  54284. this._manager = manager;
  54285. this._manager.sprites.push(this);
  54286. this.position = BABYLON.Vector3.Zero();
  54287. }
  54288. Object.defineProperty(Sprite.prototype, "size", {
  54289. get: function () {
  54290. return this.width;
  54291. },
  54292. set: function (value) {
  54293. this.width = value;
  54294. this.height = value;
  54295. },
  54296. enumerable: true,
  54297. configurable: true
  54298. });
  54299. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54300. this._fromIndex = from;
  54301. this._toIndex = to;
  54302. this._loopAnimation = loop;
  54303. this._delay = delay;
  54304. this._animationStarted = true;
  54305. this._direction = from < to ? 1 : -1;
  54306. this.cellIndex = from;
  54307. this._time = 0;
  54308. this._onAnimationEnd = onAnimationEnd;
  54309. };
  54310. Sprite.prototype.stopAnimation = function () {
  54311. this._animationStarted = false;
  54312. };
  54313. /** @hidden */
  54314. Sprite.prototype._animate = function (deltaTime) {
  54315. if (!this._animationStarted)
  54316. return;
  54317. this._time += deltaTime;
  54318. if (this._time > this._delay) {
  54319. this._time = this._time % this._delay;
  54320. this.cellIndex += this._direction;
  54321. if (this.cellIndex > this._toIndex) {
  54322. if (this._loopAnimation) {
  54323. this.cellIndex = this._fromIndex;
  54324. }
  54325. else {
  54326. this.cellIndex = this._toIndex;
  54327. this._animationStarted = false;
  54328. if (this._onAnimationEnd) {
  54329. this._onAnimationEnd();
  54330. }
  54331. if (this.disposeWhenFinishedAnimating) {
  54332. this.dispose();
  54333. }
  54334. }
  54335. }
  54336. }
  54337. };
  54338. Sprite.prototype.dispose = function () {
  54339. for (var i = 0; i < this._manager.sprites.length; i++) {
  54340. if (this._manager.sprites[i] == this) {
  54341. this._manager.sprites.splice(i, 1);
  54342. }
  54343. }
  54344. };
  54345. return Sprite;
  54346. }());
  54347. BABYLON.Sprite = Sprite;
  54348. })(BABYLON || (BABYLON = {}));
  54349. //# sourceMappingURL=babylon.sprite.js.map
  54350. var BABYLON;
  54351. (function (BABYLON) {
  54352. var IntersectionInfo = /** @class */ (function () {
  54353. function IntersectionInfo(bu, bv, distance) {
  54354. this.bu = bu;
  54355. this.bv = bv;
  54356. this.distance = distance;
  54357. this.faceId = 0;
  54358. this.subMeshId = 0;
  54359. }
  54360. return IntersectionInfo;
  54361. }());
  54362. BABYLON.IntersectionInfo = IntersectionInfo;
  54363. /**
  54364. * Information about the result of picking within a scene
  54365. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54366. */
  54367. var PickingInfo = /** @class */ (function () {
  54368. function PickingInfo() {
  54369. /**
  54370. * If the pick collided with an object
  54371. */
  54372. this.hit = false;
  54373. /**
  54374. * Distance away where the pick collided
  54375. */
  54376. this.distance = 0;
  54377. /**
  54378. * The location of pick collision
  54379. */
  54380. this.pickedPoint = null;
  54381. /**
  54382. * The mesh corresponding the the pick collision
  54383. */
  54384. this.pickedMesh = null;
  54385. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54386. this.bu = 0;
  54387. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54388. this.bv = 0;
  54389. /** The id of the face on the mesh that was picked */
  54390. this.faceId = -1;
  54391. /** Id of the the submesh that was picked */
  54392. this.subMeshId = 0;
  54393. /** If a sprite was picked, this will be the sprite the pick collided with */
  54394. this.pickedSprite = null;
  54395. /**
  54396. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54397. */
  54398. this.originMesh = null;
  54399. /**
  54400. * The ray that was used to perform the picking.
  54401. */
  54402. this.ray = null;
  54403. }
  54404. /**
  54405. * Gets the normal correspodning to the face the pick collided with
  54406. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54407. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54408. * @returns The normal correspodning to the face the pick collided with
  54409. */
  54410. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54411. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54412. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54413. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54414. return null;
  54415. }
  54416. var indices = this.pickedMesh.getIndices();
  54417. if (!indices) {
  54418. return null;
  54419. }
  54420. var result;
  54421. if (useVerticesNormals) {
  54422. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54423. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54424. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54425. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54426. normal0 = normal0.scale(this.bu);
  54427. normal1 = normal1.scale(this.bv);
  54428. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54429. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54430. }
  54431. else {
  54432. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54433. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54434. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54435. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54436. var p1p2 = vertex1.subtract(vertex2);
  54437. var p3p2 = vertex3.subtract(vertex2);
  54438. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54439. }
  54440. if (useWorldCoordinates) {
  54441. var wm = this.pickedMesh.getWorldMatrix();
  54442. if (this.pickedMesh.nonUniformScaling) {
  54443. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54444. wm = BABYLON.Tmp.Matrix[0];
  54445. wm.setTranslationFromFloats(0, 0, 0);
  54446. wm.invert();
  54447. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54448. wm = BABYLON.Tmp.Matrix[1];
  54449. }
  54450. result = BABYLON.Vector3.TransformNormal(result, wm);
  54451. }
  54452. result.normalize();
  54453. return result;
  54454. };
  54455. /**
  54456. * Gets the texture coordinates of where the pick occured
  54457. * @returns the vector containing the coordnates of the texture
  54458. */
  54459. PickingInfo.prototype.getTextureCoordinates = function () {
  54460. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54461. return null;
  54462. }
  54463. var indices = this.pickedMesh.getIndices();
  54464. if (!indices) {
  54465. return null;
  54466. }
  54467. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54468. if (!uvs) {
  54469. return null;
  54470. }
  54471. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54472. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54473. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54474. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54475. uv1 = uv1.scale(this.bu);
  54476. uv2 = uv2.scale(this.bv);
  54477. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54478. };
  54479. return PickingInfo;
  54480. }());
  54481. BABYLON.PickingInfo = PickingInfo;
  54482. })(BABYLON || (BABYLON = {}));
  54483. //# sourceMappingURL=babylon.pickingInfo.js.map
  54484. var BABYLON;
  54485. (function (BABYLON) {
  54486. var Ray = /** @class */ (function () {
  54487. function Ray(origin, direction, length) {
  54488. if (length === void 0) { length = Number.MAX_VALUE; }
  54489. this.origin = origin;
  54490. this.direction = direction;
  54491. this.length = length;
  54492. }
  54493. // Methods
  54494. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54495. var d = 0.0;
  54496. var maxValue = Number.MAX_VALUE;
  54497. var inv;
  54498. var min;
  54499. var max;
  54500. var temp;
  54501. if (Math.abs(this.direction.x) < 0.0000001) {
  54502. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54503. return false;
  54504. }
  54505. }
  54506. else {
  54507. inv = 1.0 / this.direction.x;
  54508. min = (minimum.x - this.origin.x) * inv;
  54509. max = (maximum.x - this.origin.x) * inv;
  54510. if (max === -Infinity) {
  54511. max = Infinity;
  54512. }
  54513. if (min > max) {
  54514. temp = min;
  54515. min = max;
  54516. max = temp;
  54517. }
  54518. d = Math.max(min, d);
  54519. maxValue = Math.min(max, maxValue);
  54520. if (d > maxValue) {
  54521. return false;
  54522. }
  54523. }
  54524. if (Math.abs(this.direction.y) < 0.0000001) {
  54525. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54526. return false;
  54527. }
  54528. }
  54529. else {
  54530. inv = 1.0 / this.direction.y;
  54531. min = (minimum.y - this.origin.y) * inv;
  54532. max = (maximum.y - this.origin.y) * inv;
  54533. if (max === -Infinity) {
  54534. max = Infinity;
  54535. }
  54536. if (min > max) {
  54537. temp = min;
  54538. min = max;
  54539. max = temp;
  54540. }
  54541. d = Math.max(min, d);
  54542. maxValue = Math.min(max, maxValue);
  54543. if (d > maxValue) {
  54544. return false;
  54545. }
  54546. }
  54547. if (Math.abs(this.direction.z) < 0.0000001) {
  54548. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54549. return false;
  54550. }
  54551. }
  54552. else {
  54553. inv = 1.0 / this.direction.z;
  54554. min = (minimum.z - this.origin.z) * inv;
  54555. max = (maximum.z - this.origin.z) * inv;
  54556. if (max === -Infinity) {
  54557. max = Infinity;
  54558. }
  54559. if (min > max) {
  54560. temp = min;
  54561. min = max;
  54562. max = temp;
  54563. }
  54564. d = Math.max(min, d);
  54565. maxValue = Math.min(max, maxValue);
  54566. if (d > maxValue) {
  54567. return false;
  54568. }
  54569. }
  54570. return true;
  54571. };
  54572. Ray.prototype.intersectsBox = function (box) {
  54573. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54574. };
  54575. Ray.prototype.intersectsSphere = function (sphere) {
  54576. var x = sphere.center.x - this.origin.x;
  54577. var y = sphere.center.y - this.origin.y;
  54578. var z = sphere.center.z - this.origin.z;
  54579. var pyth = (x * x) + (y * y) + (z * z);
  54580. var rr = sphere.radius * sphere.radius;
  54581. if (pyth <= rr) {
  54582. return true;
  54583. }
  54584. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54585. if (dot < 0.0) {
  54586. return false;
  54587. }
  54588. var temp = pyth - (dot * dot);
  54589. return temp <= rr;
  54590. };
  54591. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54592. if (!this._edge1) {
  54593. this._edge1 = BABYLON.Vector3.Zero();
  54594. this._edge2 = BABYLON.Vector3.Zero();
  54595. this._pvec = BABYLON.Vector3.Zero();
  54596. this._tvec = BABYLON.Vector3.Zero();
  54597. this._qvec = BABYLON.Vector3.Zero();
  54598. }
  54599. vertex1.subtractToRef(vertex0, this._edge1);
  54600. vertex2.subtractToRef(vertex0, this._edge2);
  54601. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54602. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54603. if (det === 0) {
  54604. return null;
  54605. }
  54606. var invdet = 1 / det;
  54607. this.origin.subtractToRef(vertex0, this._tvec);
  54608. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54609. if (bu < 0 || bu > 1.0) {
  54610. return null;
  54611. }
  54612. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54613. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54614. if (bv < 0 || bu + bv > 1.0) {
  54615. return null;
  54616. }
  54617. //check if the distance is longer than the predefined length.
  54618. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54619. if (distance > this.length) {
  54620. return null;
  54621. }
  54622. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54623. };
  54624. Ray.prototype.intersectsPlane = function (plane) {
  54625. var distance;
  54626. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54627. if (Math.abs(result1) < 9.99999997475243E-07) {
  54628. return null;
  54629. }
  54630. else {
  54631. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54632. distance = (-plane.d - result2) / result1;
  54633. if (distance < 0.0) {
  54634. if (distance < -9.99999997475243E-07) {
  54635. return null;
  54636. }
  54637. else {
  54638. return 0;
  54639. }
  54640. }
  54641. return distance;
  54642. }
  54643. };
  54644. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54645. var tm = BABYLON.Tmp.Matrix[0];
  54646. mesh.getWorldMatrix().invertToRef(tm);
  54647. if (this._tmpRay) {
  54648. Ray.TransformToRef(this, tm, this._tmpRay);
  54649. }
  54650. else {
  54651. this._tmpRay = Ray.Transform(this, tm);
  54652. }
  54653. return mesh.intersects(this._tmpRay, fastCheck);
  54654. };
  54655. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54656. if (results) {
  54657. results.length = 0;
  54658. }
  54659. else {
  54660. results = [];
  54661. }
  54662. for (var i = 0; i < meshes.length; i++) {
  54663. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54664. if (pickInfo.hit) {
  54665. results.push(pickInfo);
  54666. }
  54667. }
  54668. results.sort(this._comparePickingInfo);
  54669. return results;
  54670. };
  54671. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54672. if (pickingInfoA.distance < pickingInfoB.distance) {
  54673. return -1;
  54674. }
  54675. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54676. return 1;
  54677. }
  54678. else {
  54679. return 0;
  54680. }
  54681. };
  54682. /**
  54683. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54684. * @param sega the first point of the segment to test the intersection against
  54685. * @param segb the second point of the segment to test the intersection against
  54686. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54687. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54688. */
  54689. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54690. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54691. var u = segb.subtract(sega);
  54692. var v = rsegb.subtract(this.origin);
  54693. var w = sega.subtract(this.origin);
  54694. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54695. var b = BABYLON.Vector3.Dot(u, v);
  54696. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54697. var d = BABYLON.Vector3.Dot(u, w);
  54698. var e = BABYLON.Vector3.Dot(v, w);
  54699. var D = a * c - b * b; // always >= 0
  54700. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54701. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54702. // compute the line parameters of the two closest points
  54703. if (D < Ray.smallnum) { // the lines are almost parallel
  54704. sN = 0.0; // force using point P0 on segment S1
  54705. sD = 1.0; // to prevent possible division by 0.0 later
  54706. tN = e;
  54707. tD = c;
  54708. }
  54709. else { // get the closest points on the infinite lines
  54710. sN = (b * e - c * d);
  54711. tN = (a * e - b * d);
  54712. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54713. sN = 0.0;
  54714. tN = e;
  54715. tD = c;
  54716. }
  54717. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54718. sN = sD;
  54719. tN = e + b;
  54720. tD = c;
  54721. }
  54722. }
  54723. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54724. tN = 0.0;
  54725. // recompute sc for this edge
  54726. if (-d < 0.0) {
  54727. sN = 0.0;
  54728. }
  54729. else if (-d > a)
  54730. sN = sD;
  54731. else {
  54732. sN = -d;
  54733. sD = a;
  54734. }
  54735. }
  54736. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54737. tN = tD;
  54738. // recompute sc for this edge
  54739. if ((-d + b) < 0.0) {
  54740. sN = 0;
  54741. }
  54742. else if ((-d + b) > a) {
  54743. sN = sD;
  54744. }
  54745. else {
  54746. sN = (-d + b);
  54747. sD = a;
  54748. }
  54749. }
  54750. // finally do the division to get sc and tc
  54751. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54752. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54753. // get the difference of the two closest points
  54754. var qtc = v.multiplyByFloats(tc, tc, tc);
  54755. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54756. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54757. if (isIntersected) {
  54758. return qtc.length();
  54759. }
  54760. return -1;
  54761. };
  54762. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54763. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54764. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54765. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54766. this.direction.normalize();
  54767. return this;
  54768. };
  54769. // Statics
  54770. Ray.Zero = function () {
  54771. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54772. };
  54773. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54774. var result = Ray.Zero();
  54775. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54776. };
  54777. /**
  54778. * 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
  54779. * transformed to the given world matrix.
  54780. * @param origin The origin point
  54781. * @param end The end point
  54782. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54783. */
  54784. Ray.CreateNewFromTo = function (origin, end, world) {
  54785. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54786. var direction = end.subtract(origin);
  54787. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54788. direction.normalize();
  54789. return Ray.Transform(new Ray(origin, direction, length), world);
  54790. };
  54791. Ray.Transform = function (ray, matrix) {
  54792. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54793. Ray.TransformToRef(ray, matrix, result);
  54794. return result;
  54795. };
  54796. Ray.TransformToRef = function (ray, matrix, result) {
  54797. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54798. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54799. result.length = ray.length;
  54800. var dir = result.direction;
  54801. var len = dir.length();
  54802. if (!(len === 0 || len === 1)) {
  54803. var num = 1.0 / len;
  54804. dir.x *= num;
  54805. dir.y *= num;
  54806. dir.z *= num;
  54807. result.length *= len;
  54808. }
  54809. };
  54810. Ray.smallnum = 0.00000001;
  54811. Ray.rayl = 10e8;
  54812. return Ray;
  54813. }());
  54814. BABYLON.Ray = Ray;
  54815. })(BABYLON || (BABYLON = {}));
  54816. //# sourceMappingURL=babylon.ray.js.map
  54817. var BABYLON;
  54818. (function (BABYLON) {
  54819. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54820. if (boxMin.x > sphereCenter.x + sphereRadius)
  54821. return false;
  54822. if (sphereCenter.x - sphereRadius > boxMax.x)
  54823. return false;
  54824. if (boxMin.y > sphereCenter.y + sphereRadius)
  54825. return false;
  54826. if (sphereCenter.y - sphereRadius > boxMax.y)
  54827. return false;
  54828. if (boxMin.z > sphereCenter.z + sphereRadius)
  54829. return false;
  54830. if (sphereCenter.z - sphereRadius > boxMax.z)
  54831. return false;
  54832. return true;
  54833. };
  54834. var getLowestRoot = (function () {
  54835. var result = { root: 0, found: false };
  54836. return function (a, b, c, maxR) {
  54837. result.root = 0;
  54838. result.found = false;
  54839. var determinant = b * b - 4.0 * a * c;
  54840. if (determinant < 0)
  54841. return result;
  54842. var sqrtD = Math.sqrt(determinant);
  54843. var r1 = (-b - sqrtD) / (2.0 * a);
  54844. var r2 = (-b + sqrtD) / (2.0 * a);
  54845. if (r1 > r2) {
  54846. var temp = r2;
  54847. r2 = r1;
  54848. r1 = temp;
  54849. }
  54850. if (r1 > 0 && r1 < maxR) {
  54851. result.root = r1;
  54852. result.found = true;
  54853. return result;
  54854. }
  54855. if (r2 > 0 && r2 < maxR) {
  54856. result.root = r2;
  54857. result.found = true;
  54858. return result;
  54859. }
  54860. return result;
  54861. };
  54862. })();
  54863. var Collider = /** @class */ (function () {
  54864. function Collider() {
  54865. this._collisionPoint = BABYLON.Vector3.Zero();
  54866. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54867. this._tempVector = BABYLON.Vector3.Zero();
  54868. this._tempVector2 = BABYLON.Vector3.Zero();
  54869. this._tempVector3 = BABYLON.Vector3.Zero();
  54870. this._tempVector4 = BABYLON.Vector3.Zero();
  54871. this._edge = BABYLON.Vector3.Zero();
  54872. this._baseToVertex = BABYLON.Vector3.Zero();
  54873. this._destinationPoint = BABYLON.Vector3.Zero();
  54874. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54875. this._displacementVector = BABYLON.Vector3.Zero();
  54876. /** @hidden */
  54877. this._radius = BABYLON.Vector3.One();
  54878. /** @hidden */
  54879. this._retry = 0;
  54880. /** @hidden */
  54881. this._basePointWorld = BABYLON.Vector3.Zero();
  54882. this._velocityWorld = BABYLON.Vector3.Zero();
  54883. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54884. this._collisionMask = -1;
  54885. }
  54886. Object.defineProperty(Collider.prototype, "collisionMask", {
  54887. get: function () {
  54888. return this._collisionMask;
  54889. },
  54890. set: function (mask) {
  54891. this._collisionMask = !isNaN(mask) ? mask : -1;
  54892. },
  54893. enumerable: true,
  54894. configurable: true
  54895. });
  54896. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54897. /**
  54898. * Gets the plane normal used to compute the sliding response (in local space)
  54899. */
  54900. get: function () {
  54901. return this._slidePlaneNormal;
  54902. },
  54903. enumerable: true,
  54904. configurable: true
  54905. });
  54906. // Methods
  54907. /** @hidden */
  54908. Collider.prototype._initialize = function (source, dir, e) {
  54909. this._velocity = dir;
  54910. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54911. this._basePoint = source;
  54912. source.multiplyToRef(this._radius, this._basePointWorld);
  54913. dir.multiplyToRef(this._radius, this._velocityWorld);
  54914. this._velocityWorldLength = this._velocityWorld.length();
  54915. this._epsilon = e;
  54916. this.collisionFound = false;
  54917. };
  54918. /** @hidden */
  54919. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54920. pa.subtractToRef(point, this._tempVector);
  54921. pb.subtractToRef(point, this._tempVector2);
  54922. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54923. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54924. if (d < 0)
  54925. return false;
  54926. pc.subtractToRef(point, this._tempVector3);
  54927. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54928. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54929. if (d < 0)
  54930. return false;
  54931. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54932. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54933. return d >= 0;
  54934. };
  54935. /** @hidden */
  54936. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54937. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54938. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54939. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54940. return false;
  54941. }
  54942. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54943. return false;
  54944. return true;
  54945. };
  54946. /** @hidden */
  54947. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54948. var t0;
  54949. var embeddedInPlane = false;
  54950. //defensive programming, actually not needed.
  54951. if (!trianglePlaneArray) {
  54952. trianglePlaneArray = [];
  54953. }
  54954. if (!trianglePlaneArray[faceIndex]) {
  54955. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54956. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54957. }
  54958. var trianglePlane = trianglePlaneArray[faceIndex];
  54959. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54960. return;
  54961. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54962. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54963. if (normalDotVelocity == 0) {
  54964. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54965. return;
  54966. embeddedInPlane = true;
  54967. t0 = 0;
  54968. }
  54969. else {
  54970. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54971. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54972. if (t0 > t1) {
  54973. var temp = t1;
  54974. t1 = t0;
  54975. t0 = temp;
  54976. }
  54977. if (t0 > 1.0 || t1 < 0.0)
  54978. return;
  54979. if (t0 < 0)
  54980. t0 = 0;
  54981. if (t0 > 1.0)
  54982. t0 = 1.0;
  54983. }
  54984. this._collisionPoint.copyFromFloats(0, 0, 0);
  54985. var found = false;
  54986. var t = 1.0;
  54987. if (!embeddedInPlane) {
  54988. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54989. this._velocity.scaleToRef(t0, this._tempVector);
  54990. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54991. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54992. found = true;
  54993. t = t0;
  54994. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54995. }
  54996. }
  54997. if (!found) {
  54998. var velocitySquaredLength = this._velocity.lengthSquared();
  54999. var a = velocitySquaredLength;
  55000. this._basePoint.subtractToRef(p1, this._tempVector);
  55001. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55002. var c = this._tempVector.lengthSquared() - 1.0;
  55003. var lowestRoot = getLowestRoot(a, b, c, t);
  55004. if (lowestRoot.found) {
  55005. t = lowestRoot.root;
  55006. found = true;
  55007. this._collisionPoint.copyFrom(p1);
  55008. }
  55009. this._basePoint.subtractToRef(p2, this._tempVector);
  55010. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55011. c = this._tempVector.lengthSquared() - 1.0;
  55012. lowestRoot = getLowestRoot(a, b, c, t);
  55013. if (lowestRoot.found) {
  55014. t = lowestRoot.root;
  55015. found = true;
  55016. this._collisionPoint.copyFrom(p2);
  55017. }
  55018. this._basePoint.subtractToRef(p3, this._tempVector);
  55019. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55020. c = this._tempVector.lengthSquared() - 1.0;
  55021. lowestRoot = getLowestRoot(a, b, c, t);
  55022. if (lowestRoot.found) {
  55023. t = lowestRoot.root;
  55024. found = true;
  55025. this._collisionPoint.copyFrom(p3);
  55026. }
  55027. p2.subtractToRef(p1, this._edge);
  55028. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55029. var edgeSquaredLength = this._edge.lengthSquared();
  55030. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55031. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55032. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55033. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55034. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55035. lowestRoot = getLowestRoot(a, b, c, t);
  55036. if (lowestRoot.found) {
  55037. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55038. if (f >= 0.0 && f <= 1.0) {
  55039. t = lowestRoot.root;
  55040. found = true;
  55041. this._edge.scaleInPlace(f);
  55042. p1.addToRef(this._edge, this._collisionPoint);
  55043. }
  55044. }
  55045. p3.subtractToRef(p2, this._edge);
  55046. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55047. edgeSquaredLength = this._edge.lengthSquared();
  55048. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55049. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55050. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55051. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55052. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55053. lowestRoot = getLowestRoot(a, b, c, t);
  55054. if (lowestRoot.found) {
  55055. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55056. if (f >= 0.0 && f <= 1.0) {
  55057. t = lowestRoot.root;
  55058. found = true;
  55059. this._edge.scaleInPlace(f);
  55060. p2.addToRef(this._edge, this._collisionPoint);
  55061. }
  55062. }
  55063. p1.subtractToRef(p3, this._edge);
  55064. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55065. edgeSquaredLength = this._edge.lengthSquared();
  55066. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55067. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55068. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55069. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55070. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55071. lowestRoot = getLowestRoot(a, b, c, t);
  55072. if (lowestRoot.found) {
  55073. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55074. if (f >= 0.0 && f <= 1.0) {
  55075. t = lowestRoot.root;
  55076. found = true;
  55077. this._edge.scaleInPlace(f);
  55078. p3.addToRef(this._edge, this._collisionPoint);
  55079. }
  55080. }
  55081. }
  55082. if (found) {
  55083. var distToCollision = t * this._velocity.length();
  55084. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55085. if (!this.intersectionPoint) {
  55086. this.intersectionPoint = this._collisionPoint.clone();
  55087. }
  55088. else {
  55089. this.intersectionPoint.copyFrom(this._collisionPoint);
  55090. }
  55091. this._nearestDistance = distToCollision;
  55092. this.collisionFound = true;
  55093. }
  55094. }
  55095. };
  55096. /** @hidden */
  55097. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55098. for (var i = indexStart; i < indexEnd; i += 3) {
  55099. var p1 = pts[indices[i] - decal];
  55100. var p2 = pts[indices[i + 1] - decal];
  55101. var p3 = pts[indices[i + 2] - decal];
  55102. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55103. }
  55104. };
  55105. /** @hidden */
  55106. Collider.prototype._getResponse = function (pos, vel) {
  55107. pos.addToRef(vel, this._destinationPoint);
  55108. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55109. this._basePoint.addToRef(vel, pos);
  55110. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55111. this._slidePlaneNormal.normalize();
  55112. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55113. pos.addInPlace(this._displacementVector);
  55114. this.intersectionPoint.addInPlace(this._displacementVector);
  55115. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55116. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55117. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55118. };
  55119. return Collider;
  55120. }());
  55121. BABYLON.Collider = Collider;
  55122. })(BABYLON || (BABYLON = {}));
  55123. //# sourceMappingURL=babylon.collider.js.map
  55124. var BABYLON;
  55125. (function (BABYLON) {
  55126. //WebWorker code will be inserted to this variable.
  55127. BABYLON.CollisionWorker = "";
  55128. /** Defines supported task for worker process */
  55129. var WorkerTaskType;
  55130. (function (WorkerTaskType) {
  55131. /** Initialization */
  55132. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55133. /** Update of geometry */
  55134. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55135. /** Evaluate collision */
  55136. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55137. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55138. /** Defines kind of replies returned by worker */
  55139. var WorkerReplyType;
  55140. (function (WorkerReplyType) {
  55141. /** Success */
  55142. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55143. /** Unkown error */
  55144. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55145. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55146. var CollisionCoordinatorWorker = /** @class */ (function () {
  55147. function CollisionCoordinatorWorker() {
  55148. var _this = this;
  55149. this._scaledPosition = BABYLON.Vector3.Zero();
  55150. this._scaledVelocity = BABYLON.Vector3.Zero();
  55151. this.onMeshUpdated = function (transformNode) {
  55152. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55153. };
  55154. this.onGeometryUpdated = function (geometry) {
  55155. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55156. };
  55157. this._afterRender = function () {
  55158. if (!_this._init)
  55159. return;
  55160. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55161. return;
  55162. }
  55163. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55164. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55165. if (_this._runningUpdated > 4) {
  55166. return;
  55167. }
  55168. ++_this._runningUpdated;
  55169. var payload = {
  55170. updatedMeshes: _this._addUpdateMeshesList,
  55171. updatedGeometries: _this._addUpdateGeometriesList,
  55172. removedGeometries: _this._toRemoveGeometryArray,
  55173. removedMeshes: _this._toRemoveMeshesArray
  55174. };
  55175. var message = {
  55176. payload: payload,
  55177. taskType: WorkerTaskType.UPDATE
  55178. };
  55179. var serializable = [];
  55180. for (var id in payload.updatedGeometries) {
  55181. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55182. //prepare transferables
  55183. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55184. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55185. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55186. }
  55187. }
  55188. _this._worker.postMessage(message, serializable);
  55189. _this._addUpdateMeshesList = {};
  55190. _this._addUpdateGeometriesList = {};
  55191. _this._toRemoveGeometryArray = [];
  55192. _this._toRemoveMeshesArray = [];
  55193. };
  55194. this._onMessageFromWorker = function (e) {
  55195. var returnData = e.data;
  55196. if (returnData.error != WorkerReplyType.SUCCESS) {
  55197. //TODO what errors can be returned from the worker?
  55198. BABYLON.Tools.Warn("error returned from worker!");
  55199. return;
  55200. }
  55201. switch (returnData.taskType) {
  55202. case WorkerTaskType.INIT:
  55203. _this._init = true;
  55204. //Update the worked with ALL of the scene's current state
  55205. _this._scene.meshes.forEach(function (mesh) {
  55206. _this.onMeshAdded(mesh);
  55207. });
  55208. _this._scene.getGeometries().forEach(function (geometry) {
  55209. _this.onGeometryAdded(geometry);
  55210. });
  55211. break;
  55212. case WorkerTaskType.UPDATE:
  55213. _this._runningUpdated--;
  55214. break;
  55215. case WorkerTaskType.COLLIDE:
  55216. var returnPayload = returnData.payload;
  55217. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55218. return;
  55219. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55220. if (callback) {
  55221. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55222. if (mesh) {
  55223. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55224. }
  55225. }
  55226. //cleanup
  55227. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55228. break;
  55229. }
  55230. };
  55231. this._collisionsCallbackArray = [];
  55232. this._init = false;
  55233. this._runningUpdated = 0;
  55234. this._addUpdateMeshesList = {};
  55235. this._addUpdateGeometriesList = {};
  55236. this._toRemoveGeometryArray = [];
  55237. this._toRemoveMeshesArray = [];
  55238. }
  55239. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55240. if (!this._init)
  55241. return;
  55242. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55243. return;
  55244. position.divideToRef(collider._radius, this._scaledPosition);
  55245. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55246. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55247. var payload = {
  55248. collider: {
  55249. position: this._scaledPosition.asArray(),
  55250. velocity: this._scaledVelocity.asArray(),
  55251. radius: collider._radius.asArray()
  55252. },
  55253. collisionId: collisionIndex,
  55254. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55255. maximumRetry: maximumRetry
  55256. };
  55257. var message = {
  55258. payload: payload,
  55259. taskType: WorkerTaskType.COLLIDE
  55260. };
  55261. this._worker.postMessage(message);
  55262. };
  55263. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55264. this._scene = scene;
  55265. this._scene.registerAfterRender(this._afterRender);
  55266. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55267. this._worker = new Worker(workerUrl);
  55268. this._worker.onmessage = this._onMessageFromWorker;
  55269. var message = {
  55270. payload: {},
  55271. taskType: WorkerTaskType.INIT
  55272. };
  55273. this._worker.postMessage(message);
  55274. };
  55275. CollisionCoordinatorWorker.prototype.destroy = function () {
  55276. this._scene.unregisterAfterRender(this._afterRender);
  55277. this._worker.terminate();
  55278. };
  55279. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55280. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55281. this.onMeshUpdated(mesh);
  55282. };
  55283. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55284. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55285. };
  55286. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55287. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55288. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55289. this.onGeometryUpdated(geometry);
  55290. };
  55291. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55292. this._toRemoveGeometryArray.push(geometry.id);
  55293. };
  55294. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55295. var submeshes = [];
  55296. if (mesh.subMeshes) {
  55297. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55298. var boundingInfo = sm.getBoundingInfo();
  55299. return {
  55300. position: idx,
  55301. verticesStart: sm.verticesStart,
  55302. verticesCount: sm.verticesCount,
  55303. indexStart: sm.indexStart,
  55304. indexCount: sm.indexCount,
  55305. hasMaterial: !!sm.getMaterial(),
  55306. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55307. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55308. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55309. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55310. };
  55311. });
  55312. }
  55313. var geometryId = null;
  55314. if (mesh instanceof BABYLON.Mesh) {
  55315. var geometry = mesh.geometry;
  55316. geometryId = geometry ? geometry.id : null;
  55317. }
  55318. else if (mesh instanceof BABYLON.InstancedMesh) {
  55319. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55320. geometryId = geometry ? geometry.id : null;
  55321. }
  55322. var boundingInfo = mesh.getBoundingInfo();
  55323. return {
  55324. uniqueId: mesh.uniqueId,
  55325. id: mesh.id,
  55326. name: mesh.name,
  55327. geometryId: geometryId,
  55328. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55329. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55330. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55331. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55332. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55333. subMeshes: submeshes,
  55334. checkCollisions: mesh.checkCollisions
  55335. };
  55336. };
  55337. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55338. return {
  55339. id: geometry.id,
  55340. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55341. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55342. indices: new Uint32Array(geometry.getIndices() || []),
  55343. };
  55344. };
  55345. return CollisionCoordinatorWorker;
  55346. }());
  55347. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55348. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55349. function CollisionCoordinatorLegacy() {
  55350. this._scaledPosition = BABYLON.Vector3.Zero();
  55351. this._scaledVelocity = BABYLON.Vector3.Zero();
  55352. this._finalPosition = BABYLON.Vector3.Zero();
  55353. }
  55354. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55355. position.divideToRef(collider._radius, this._scaledPosition);
  55356. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55357. collider.collidedMesh = null;
  55358. collider._retry = 0;
  55359. collider._initialVelocity = this._scaledVelocity;
  55360. collider._initialPosition = this._scaledPosition;
  55361. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55362. this._finalPosition.multiplyInPlace(collider._radius);
  55363. //run the callback
  55364. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55365. };
  55366. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55367. this._scene = scene;
  55368. };
  55369. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55370. //Legacy need no destruction method.
  55371. };
  55372. //No update in legacy mode
  55373. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55374. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55375. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55376. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55377. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55378. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55379. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55380. if (excludedMesh === void 0) { excludedMesh = null; }
  55381. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55382. if (collider._retry >= maximumRetry) {
  55383. finalPosition.copyFrom(position);
  55384. return;
  55385. }
  55386. // Check if this is a mesh else camera or -1
  55387. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55388. collider._initialize(position, velocity, closeDistance);
  55389. // Check all meshes
  55390. for (var index = 0; index < this._scene.meshes.length; index++) {
  55391. var mesh = this._scene.meshes[index];
  55392. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55393. mesh._checkCollision(collider);
  55394. }
  55395. }
  55396. if (!collider.collisionFound) {
  55397. position.addToRef(velocity, finalPosition);
  55398. return;
  55399. }
  55400. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55401. collider._getResponse(position, velocity);
  55402. }
  55403. if (velocity.length() <= closeDistance) {
  55404. finalPosition.copyFrom(position);
  55405. return;
  55406. }
  55407. collider._retry++;
  55408. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55409. };
  55410. return CollisionCoordinatorLegacy;
  55411. }());
  55412. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55413. })(BABYLON || (BABYLON = {}));
  55414. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55415. var BABYLON;
  55416. (function (BABYLON) {
  55417. /**
  55418. * A particle represents one of the element emitted by a particle system.
  55419. * This is mainly define by its coordinates, direction, velocity and age.
  55420. */
  55421. var Particle = /** @class */ (function () {
  55422. /**
  55423. * Creates a new instance Particle
  55424. * @param particleSystem the particle system the particle belongs to
  55425. */
  55426. function Particle(
  55427. /**
  55428. * particleSystem the particle system the particle belongs to.
  55429. */
  55430. particleSystem) {
  55431. this.particleSystem = particleSystem;
  55432. /**
  55433. * The world position of the particle in the scene.
  55434. */
  55435. this.position = BABYLON.Vector3.Zero();
  55436. /**
  55437. * The world direction of the particle in the scene.
  55438. */
  55439. this.direction = BABYLON.Vector3.Zero();
  55440. /**
  55441. * The color of the particle.
  55442. */
  55443. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55444. /**
  55445. * The color change of the particle per step.
  55446. */
  55447. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55448. /**
  55449. * Defines how long will the life of the particle be.
  55450. */
  55451. this.lifeTime = 1.0;
  55452. /**
  55453. * The current age of the particle.
  55454. */
  55455. this.age = 0;
  55456. /**
  55457. * The current size of the particle.
  55458. */
  55459. this.size = 0;
  55460. /**
  55461. * The current scale of the particle.
  55462. */
  55463. this.scale = new BABYLON.Vector2(1, 1);
  55464. /**
  55465. * The current angle of the particle.
  55466. */
  55467. this.angle = 0;
  55468. /**
  55469. * Defines how fast is the angle changing.
  55470. */
  55471. this.angularSpeed = 0;
  55472. /**
  55473. * Defines the cell index used by the particle to be rendered from a sprite.
  55474. */
  55475. this.cellIndex = 0;
  55476. /** @hidden */
  55477. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55478. /** @hidden */
  55479. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55480. /** @hidden */
  55481. this._currentSize1 = 0;
  55482. /** @hidden */
  55483. this._currentSize2 = 0;
  55484. /** @hidden */
  55485. this._currentAngularSpeed1 = 0;
  55486. /** @hidden */
  55487. this._currentAngularSpeed2 = 0;
  55488. /** @hidden */
  55489. this._currentVelocity1 = 0;
  55490. /** @hidden */
  55491. this._currentVelocity2 = 0;
  55492. /** @hidden */
  55493. this._currentLimitVelocity1 = 0;
  55494. /** @hidden */
  55495. this._currentLimitVelocity2 = 0;
  55496. /** @hidden */
  55497. this._currentDrag1 = 0;
  55498. /** @hidden */
  55499. this._currentDrag2 = 0;
  55500. if (!this.particleSystem.isAnimationSheetEnabled) {
  55501. return;
  55502. }
  55503. this.updateCellInfoFromSystem();
  55504. }
  55505. Particle.prototype.updateCellInfoFromSystem = function () {
  55506. this.cellIndex = this.particleSystem.startSpriteCellID;
  55507. };
  55508. /**
  55509. * Defines how the sprite cell index is updated for the particle
  55510. */
  55511. Particle.prototype.updateCellIndex = function () {
  55512. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55513. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55514. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55515. };
  55516. /**
  55517. * Copy the properties of particle to another one.
  55518. * @param other the particle to copy the information to.
  55519. */
  55520. Particle.prototype.copyTo = function (other) {
  55521. other.position.copyFrom(this.position);
  55522. if (this._initialDirection) {
  55523. if (other._initialDirection) {
  55524. other._initialDirection.copyFrom(this._initialDirection);
  55525. }
  55526. else {
  55527. other._initialDirection = this._initialDirection.clone();
  55528. }
  55529. }
  55530. else {
  55531. other._initialDirection = null;
  55532. }
  55533. other.direction.copyFrom(this.direction);
  55534. other.color.copyFrom(this.color);
  55535. other.colorStep.copyFrom(this.colorStep);
  55536. other.lifeTime = this.lifeTime;
  55537. other.age = this.age;
  55538. other.size = this.size;
  55539. other.scale.copyFrom(this.scale);
  55540. other.angle = this.angle;
  55541. other.angularSpeed = this.angularSpeed;
  55542. other.particleSystem = this.particleSystem;
  55543. other.cellIndex = this.cellIndex;
  55544. if (this._currentColorGradient) {
  55545. other._currentColorGradient = this._currentColorGradient;
  55546. other._currentColor1.copyFrom(this._currentColor1);
  55547. other._currentColor2.copyFrom(this._currentColor2);
  55548. }
  55549. if (this._currentSizeGradient) {
  55550. other._currentSizeGradient = this._currentSizeGradient;
  55551. other._currentSize1 = this._currentSize1;
  55552. other._currentSize2 = this._currentSize2;
  55553. }
  55554. if (this._currentAngularSpeedGradient) {
  55555. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55556. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55557. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55558. }
  55559. if (this._currentVelocityGradient) {
  55560. other._currentVelocityGradient = this._currentVelocityGradient;
  55561. other._currentVelocity1 = this._currentVelocity1;
  55562. other._currentVelocity2 = this._currentVelocity2;
  55563. }
  55564. if (this._currentLimitVelocityGradient) {
  55565. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55566. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55567. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55568. }
  55569. if (this._currentDragGradient) {
  55570. other._currentDragGradient = this._currentDragGradient;
  55571. other._currentDrag1 = this._currentDrag1;
  55572. other._currentDrag2 = this._currentDrag2;
  55573. }
  55574. if (this.particleSystem.isAnimationSheetEnabled) {
  55575. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55576. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55577. }
  55578. };
  55579. return Particle;
  55580. }());
  55581. BABYLON.Particle = Particle;
  55582. })(BABYLON || (BABYLON = {}));
  55583. //# sourceMappingURL=babylon.particle.js.map
  55584. var BABYLON;
  55585. (function (BABYLON) {
  55586. /**
  55587. * This represents the base class for particle system in Babylon.
  55588. * 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.
  55589. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55590. * @example https://doc.babylonjs.com/babylon101/particles
  55591. */
  55592. var BaseParticleSystem = /** @class */ (function () {
  55593. /**
  55594. * Instantiates a particle system.
  55595. * 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.
  55596. * @param name The name of the particle system
  55597. */
  55598. function BaseParticleSystem(name) {
  55599. /**
  55600. * List of animations used by the particle system.
  55601. */
  55602. this.animations = [];
  55603. /**
  55604. * The rendering group used by the Particle system to chose when to render.
  55605. */
  55606. this.renderingGroupId = 0;
  55607. /**
  55608. * The emitter represents the Mesh or position we are attaching the particle system to.
  55609. */
  55610. this.emitter = null;
  55611. /**
  55612. * The maximum number of particles to emit per frame
  55613. */
  55614. this.emitRate = 10;
  55615. /**
  55616. * If you want to launch only a few particles at once, that can be done, as well.
  55617. */
  55618. this.manualEmitCount = -1;
  55619. /**
  55620. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55621. */
  55622. this.updateSpeed = 0.01;
  55623. /**
  55624. * The amount of time the particle system is running (depends of the overall update speed).
  55625. */
  55626. this.targetStopDuration = 0;
  55627. /**
  55628. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55629. */
  55630. this.disposeOnStop = false;
  55631. /**
  55632. * Minimum power of emitting particles.
  55633. */
  55634. this.minEmitPower = 1;
  55635. /**
  55636. * Maximum power of emitting particles.
  55637. */
  55638. this.maxEmitPower = 1;
  55639. /**
  55640. * Minimum life time of emitting particles.
  55641. */
  55642. this.minLifeTime = 1;
  55643. /**
  55644. * Maximum life time of emitting particles.
  55645. */
  55646. this.maxLifeTime = 1;
  55647. /**
  55648. * Minimum Size of emitting particles.
  55649. */
  55650. this.minSize = 1;
  55651. /**
  55652. * Maximum Size of emitting particles.
  55653. */
  55654. this.maxSize = 1;
  55655. /**
  55656. * Minimum scale of emitting particles on X axis.
  55657. */
  55658. this.minScaleX = 1;
  55659. /**
  55660. * Maximum scale of emitting particles on X axis.
  55661. */
  55662. this.maxScaleX = 1;
  55663. /**
  55664. * Minimum scale of emitting particles on Y axis.
  55665. */
  55666. this.minScaleY = 1;
  55667. /**
  55668. * Maximum scale of emitting particles on Y axis.
  55669. */
  55670. this.maxScaleY = 1;
  55671. /**
  55672. * Gets or sets the minimal initial rotation in radians.
  55673. */
  55674. this.minInitialRotation = 0;
  55675. /**
  55676. * Gets or sets the maximal initial rotation in radians.
  55677. */
  55678. this.maxInitialRotation = 0;
  55679. /**
  55680. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55681. */
  55682. this.minAngularSpeed = 0;
  55683. /**
  55684. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55685. */
  55686. this.maxAngularSpeed = 0;
  55687. /**
  55688. * The layer mask we are rendering the particles through.
  55689. */
  55690. this.layerMask = 0x0FFFFFFF;
  55691. /**
  55692. * This can help using your own shader to render the particle system.
  55693. * The according effect will be created
  55694. */
  55695. this.customShader = null;
  55696. /**
  55697. * By default particle system starts as soon as they are created. This prevents the
  55698. * automatic start to happen and let you decide when to start emitting particles.
  55699. */
  55700. this.preventAutoStart = false;
  55701. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55702. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55703. /**
  55704. * Callback triggered when the particle animation is ending.
  55705. */
  55706. this.onAnimationEnd = null;
  55707. /**
  55708. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55709. */
  55710. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55711. /**
  55712. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55713. * to override the particles.
  55714. */
  55715. this.forceDepthWrite = false;
  55716. /** 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 */
  55717. this.preWarmCycles = 0;
  55718. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55719. this.preWarmStepOffset = 1;
  55720. /**
  55721. * 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)
  55722. */
  55723. this.spriteCellChangeSpeed = 1;
  55724. /**
  55725. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55726. */
  55727. this.startSpriteCellID = 0;
  55728. /**
  55729. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55730. */
  55731. this.endSpriteCellID = 0;
  55732. /**
  55733. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55734. */
  55735. this.spriteCellWidth = 0;
  55736. /**
  55737. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55738. */
  55739. this.spriteCellHeight = 0;
  55740. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55741. this.translationPivot = new BABYLON.Vector2(0, 0);
  55742. /**
  55743. * You can use gravity if you want to give an orientation to your particles.
  55744. */
  55745. this.gravity = BABYLON.Vector3.Zero();
  55746. this._colorGradients = null;
  55747. this._sizeGradients = null;
  55748. this._lifeTimeGradients = null;
  55749. this._angularSpeedGradients = null;
  55750. this._velocityGradients = null;
  55751. this._limitVelocityGradients = null;
  55752. this._dragGradients = null;
  55753. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55754. this.limitVelocityDamping = 0.4;
  55755. /**
  55756. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55757. */
  55758. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55759. /**
  55760. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55761. */
  55762. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55763. /**
  55764. * Color the particle will have at the end of its lifetime
  55765. */
  55766. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55767. /**
  55768. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55769. */
  55770. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55771. /**
  55772. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55773. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55774. */
  55775. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55776. this._isBillboardBased = true;
  55777. /**
  55778. * Local cache of defines for image processing.
  55779. */
  55780. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55781. this.id = name;
  55782. this.name = name;
  55783. }
  55784. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55785. /**
  55786. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55787. */
  55788. get: function () {
  55789. return this._isAnimationSheetEnabled;
  55790. },
  55791. set: function (value) {
  55792. if (this._isAnimationSheetEnabled == value) {
  55793. return;
  55794. }
  55795. this._isAnimationSheetEnabled = value;
  55796. this._reset();
  55797. },
  55798. enumerable: true,
  55799. configurable: true
  55800. });
  55801. /**
  55802. * Gets the current list of drag gradients.
  55803. * You must use addDragGradient and removeDragGradient to udpate this list
  55804. * @returns the list of drag gradients
  55805. */
  55806. BaseParticleSystem.prototype.getDragGradients = function () {
  55807. return this._dragGradients;
  55808. };
  55809. /**
  55810. * Gets the current list of limit velocity gradients.
  55811. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55812. * @returns the list of limit velocity gradients
  55813. */
  55814. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55815. return this._limitVelocityGradients;
  55816. };
  55817. /**
  55818. * Gets the current list of color gradients.
  55819. * You must use addColorGradient and removeColorGradient to udpate this list
  55820. * @returns the list of color gradients
  55821. */
  55822. BaseParticleSystem.prototype.getColorGradients = function () {
  55823. return this._colorGradients;
  55824. };
  55825. /**
  55826. * Gets the current list of size gradients.
  55827. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55828. * @returns the list of size gradients
  55829. */
  55830. BaseParticleSystem.prototype.getSizeGradients = function () {
  55831. return this._sizeGradients;
  55832. };
  55833. /**
  55834. * Gets the current list of life time gradients.
  55835. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55836. * @returns the list of life time gradients
  55837. */
  55838. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55839. return this._lifeTimeGradients;
  55840. };
  55841. /**
  55842. * Gets the current list of angular speed gradients.
  55843. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55844. * @returns the list of angular speed gradients
  55845. */
  55846. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55847. return this._angularSpeedGradients;
  55848. };
  55849. /**
  55850. * Gets the current list of velocity gradients.
  55851. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55852. * @returns the list of velocity gradients
  55853. */
  55854. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55855. return this._velocityGradients;
  55856. };
  55857. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55858. /**
  55859. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55860. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55861. */
  55862. get: function () {
  55863. if (this.particleEmitterType.direction1) {
  55864. return this.particleEmitterType.direction1;
  55865. }
  55866. return BABYLON.Vector3.Zero();
  55867. },
  55868. set: function (value) {
  55869. if (this.particleEmitterType.direction1) {
  55870. this.particleEmitterType.direction1 = value;
  55871. }
  55872. },
  55873. enumerable: true,
  55874. configurable: true
  55875. });
  55876. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55877. /**
  55878. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55879. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55880. */
  55881. get: function () {
  55882. if (this.particleEmitterType.direction2) {
  55883. return this.particleEmitterType.direction2;
  55884. }
  55885. return BABYLON.Vector3.Zero();
  55886. },
  55887. set: function (value) {
  55888. if (this.particleEmitterType.direction2) {
  55889. this.particleEmitterType.direction2 = value;
  55890. }
  55891. },
  55892. enumerable: true,
  55893. configurable: true
  55894. });
  55895. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55896. /**
  55897. * 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.
  55898. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55899. */
  55900. get: function () {
  55901. if (this.particleEmitterType.minEmitBox) {
  55902. return this.particleEmitterType.minEmitBox;
  55903. }
  55904. return BABYLON.Vector3.Zero();
  55905. },
  55906. set: function (value) {
  55907. if (this.particleEmitterType.minEmitBox) {
  55908. this.particleEmitterType.minEmitBox = value;
  55909. }
  55910. },
  55911. enumerable: true,
  55912. configurable: true
  55913. });
  55914. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55915. /**
  55916. * 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.
  55917. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55918. */
  55919. get: function () {
  55920. if (this.particleEmitterType.maxEmitBox) {
  55921. return this.particleEmitterType.maxEmitBox;
  55922. }
  55923. return BABYLON.Vector3.Zero();
  55924. },
  55925. set: function (value) {
  55926. if (this.particleEmitterType.maxEmitBox) {
  55927. this.particleEmitterType.maxEmitBox = value;
  55928. }
  55929. },
  55930. enumerable: true,
  55931. configurable: true
  55932. });
  55933. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55934. /**
  55935. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55936. */
  55937. get: function () {
  55938. return this._isBillboardBased;
  55939. },
  55940. set: function (value) {
  55941. if (this._isBillboardBased === value) {
  55942. return;
  55943. }
  55944. this._isBillboardBased = value;
  55945. this._reset();
  55946. },
  55947. enumerable: true,
  55948. configurable: true
  55949. });
  55950. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55951. /**
  55952. * Gets the image processing configuration used either in this material.
  55953. */
  55954. get: function () {
  55955. return this._imageProcessingConfiguration;
  55956. },
  55957. /**
  55958. * Sets the Default image processing configuration used either in the this material.
  55959. *
  55960. * If sets to null, the scene one is in use.
  55961. */
  55962. set: function (value) {
  55963. this._attachImageProcessingConfiguration(value);
  55964. },
  55965. enumerable: true,
  55966. configurable: true
  55967. });
  55968. /**
  55969. * Attaches a new image processing configuration to the Standard Material.
  55970. * @param configuration
  55971. */
  55972. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55973. if (configuration === this._imageProcessingConfiguration) {
  55974. return;
  55975. }
  55976. // Pick the scene configuration if needed.
  55977. if (!configuration) {
  55978. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55979. }
  55980. else {
  55981. this._imageProcessingConfiguration = configuration;
  55982. }
  55983. };
  55984. /** @hidden */
  55985. BaseParticleSystem.prototype._reset = function () {
  55986. };
  55987. /**
  55988. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55989. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55990. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55991. * @returns the emitter
  55992. */
  55993. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55994. var particleEmitter = new BABYLON.PointParticleEmitter();
  55995. particleEmitter.direction1 = direction1;
  55996. particleEmitter.direction2 = direction2;
  55997. this.particleEmitterType = particleEmitter;
  55998. return particleEmitter;
  55999. };
  56000. /**
  56001. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56002. * @param radius The radius of the hemisphere to emit from
  56003. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56004. * @returns the emitter
  56005. */
  56006. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56007. if (radius === void 0) { radius = 1; }
  56008. if (radiusRange === void 0) { radiusRange = 1; }
  56009. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56010. this.particleEmitterType = particleEmitter;
  56011. return particleEmitter;
  56012. };
  56013. /**
  56014. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56015. * @param radius The radius of the sphere to emit from
  56016. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56017. * @returns the emitter
  56018. */
  56019. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56020. if (radius === void 0) { radius = 1; }
  56021. if (radiusRange === void 0) { radiusRange = 1; }
  56022. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56023. this.particleEmitterType = particleEmitter;
  56024. return particleEmitter;
  56025. };
  56026. /**
  56027. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56028. * @param radius The radius of the sphere to emit from
  56029. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56030. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56031. * @returns the emitter
  56032. */
  56033. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56034. if (radius === void 0) { radius = 1; }
  56035. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56036. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56037. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56038. this.particleEmitterType = particleEmitter;
  56039. return particleEmitter;
  56040. };
  56041. /**
  56042. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56043. * @param radius The radius of the emission cylinder
  56044. * @param height The height of the emission cylinder
  56045. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56046. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56047. * @returns the emitter
  56048. */
  56049. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56050. if (radius === void 0) { radius = 1; }
  56051. if (height === void 0) { height = 1; }
  56052. if (radiusRange === void 0) { radiusRange = 1; }
  56053. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56054. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56055. this.particleEmitterType = particleEmitter;
  56056. return particleEmitter;
  56057. };
  56058. /**
  56059. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56060. * @param radius The radius of the cone to emit from
  56061. * @param angle The base angle of the cone
  56062. * @returns the emitter
  56063. */
  56064. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56065. if (radius === void 0) { radius = 1; }
  56066. if (angle === void 0) { angle = Math.PI / 4; }
  56067. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56068. this.particleEmitterType = particleEmitter;
  56069. return particleEmitter;
  56070. };
  56071. /**
  56072. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56073. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56074. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56075. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56076. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56077. * @returns the emitter
  56078. */
  56079. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56080. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56081. this.particleEmitterType = particleEmitter;
  56082. this.direction1 = direction1;
  56083. this.direction2 = direction2;
  56084. this.minEmitBox = minEmitBox;
  56085. this.maxEmitBox = maxEmitBox;
  56086. return particleEmitter;
  56087. };
  56088. /**
  56089. * Source color is added to the destination color without alpha affecting the result.
  56090. */
  56091. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56092. /**
  56093. * Blend current color and particle color using particle’s alpha.
  56094. */
  56095. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56096. /**
  56097. * Add current color and particle color multiplied by particle’s alpha.
  56098. */
  56099. BaseParticleSystem.BLENDMODE_ADD = 2;
  56100. return BaseParticleSystem;
  56101. }());
  56102. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56103. })(BABYLON || (BABYLON = {}));
  56104. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56105. var BABYLON;
  56106. (function (BABYLON) {
  56107. /**
  56108. * This represents a particle system in Babylon.
  56109. * 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.
  56110. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56111. * @example https://doc.babylonjs.com/babylon101/particles
  56112. */
  56113. var ParticleSystem = /** @class */ (function (_super) {
  56114. __extends(ParticleSystem, _super);
  56115. /**
  56116. * Instantiates a particle system.
  56117. * 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.
  56118. * @param name The name of the particle system
  56119. * @param capacity The max number of particles alive at the same time
  56120. * @param scene The scene the particle system belongs to
  56121. * @param customEffect a custom effect used to change the way particles are rendered by default
  56122. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56123. * @param epsilon Offset used to render the particles
  56124. */
  56125. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56126. if (customEffect === void 0) { customEffect = null; }
  56127. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56128. if (epsilon === void 0) { epsilon = 0.01; }
  56129. var _this = _super.call(this, name) || this;
  56130. /**
  56131. * An event triggered when the system is disposed
  56132. */
  56133. _this.onDisposeObservable = new BABYLON.Observable();
  56134. _this._particles = new Array();
  56135. _this._stockParticles = new Array();
  56136. _this._newPartsExcess = 0;
  56137. _this._vertexBuffers = {};
  56138. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56139. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56140. _this._scaledDirection = BABYLON.Vector3.Zero();
  56141. _this._scaledGravity = BABYLON.Vector3.Zero();
  56142. _this._currentRenderId = -1;
  56143. _this._useInstancing = false;
  56144. _this._started = false;
  56145. _this._stopped = false;
  56146. _this._actualFrame = 0;
  56147. // start of sub system methods
  56148. /**
  56149. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56150. * Its lifetime will start back at 0.
  56151. */
  56152. _this.recycleParticle = function (particle) {
  56153. var lastParticle = _this._particles.pop();
  56154. if (lastParticle !== particle) {
  56155. lastParticle.copyTo(particle);
  56156. }
  56157. _this._stockParticles.push(lastParticle);
  56158. };
  56159. _this._createParticle = function () {
  56160. var particle;
  56161. if (_this._stockParticles.length !== 0) {
  56162. particle = _this._stockParticles.pop();
  56163. particle.age = 0;
  56164. particle._currentColorGradient = null;
  56165. particle.cellIndex = _this.startSpriteCellID;
  56166. }
  56167. else {
  56168. particle = new BABYLON.Particle(_this);
  56169. }
  56170. return particle;
  56171. };
  56172. _this._emitFromParticle = function (particle) {
  56173. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56174. return;
  56175. }
  56176. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56177. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56178. subSystem._rootParticleSystem = _this;
  56179. _this.activeSubSystems.push(subSystem);
  56180. subSystem.start();
  56181. };
  56182. _this._capacity = capacity;
  56183. _this._epsilon = epsilon;
  56184. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56185. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56186. // Setup the default processing configuration to the scene.
  56187. _this._attachImageProcessingConfiguration(null);
  56188. _this._customEffect = customEffect;
  56189. _this._scene.particleSystems.push(_this);
  56190. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56191. _this._createIndexBuffer();
  56192. _this._createVertexBuffers();
  56193. // Default emitter type
  56194. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56195. _this.updateFunction = function (particles) {
  56196. var noiseTextureData = null;
  56197. var noiseTextureSize = null;
  56198. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56199. noiseTextureData = (_this.noiseTexture.readPixels());
  56200. noiseTextureSize = _this.noiseTexture.getSize();
  56201. }
  56202. var _loop_1 = function () {
  56203. particle = particles[index];
  56204. particle.age += _this._scaledUpdateSpeed;
  56205. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56206. _this._emitFromParticle(particle);
  56207. _this.recycleParticle(particle);
  56208. index--;
  56209. return "continue";
  56210. }
  56211. else {
  56212. var ratio = particle.age / particle.lifeTime;
  56213. // Color
  56214. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56215. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56216. if (currentGradient !== particle._currentColorGradient) {
  56217. particle._currentColor1.copyFrom(particle._currentColor2);
  56218. nextGradient.getColorToRef(particle._currentColor2);
  56219. particle._currentColorGradient = currentGradient;
  56220. }
  56221. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56222. });
  56223. }
  56224. else {
  56225. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56226. particle.color.addInPlace(_this._scaledColorStep);
  56227. if (particle.color.a < 0) {
  56228. particle.color.a = 0;
  56229. }
  56230. }
  56231. // Angular speed
  56232. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56233. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56234. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56235. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56236. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56237. particle._currentAngularSpeedGradient = currentGradient;
  56238. }
  56239. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56240. });
  56241. }
  56242. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56243. // Direction
  56244. var directionScale_1 = _this._scaledUpdateSpeed;
  56245. /// Velocity
  56246. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56247. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56248. if (currentGradient !== particle._currentVelocityGradient) {
  56249. particle._currentVelocity1 = particle._currentVelocity2;
  56250. particle._currentVelocity2 = nextGradient.getFactor();
  56251. particle._currentVelocityGradient = currentGradient;
  56252. }
  56253. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56254. });
  56255. }
  56256. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56257. /// Limit velocity
  56258. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56259. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56260. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56261. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56262. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56263. particle._currentLimitVelocityGradient = currentGradient;
  56264. }
  56265. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56266. var currentVelocity = particle.direction.length();
  56267. if (currentVelocity > limitVelocity) {
  56268. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56269. }
  56270. });
  56271. }
  56272. /// Drag
  56273. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56274. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56275. if (currentGradient !== particle._currentDragGradient) {
  56276. particle._currentDrag1 = particle._currentDrag2;
  56277. particle._currentDrag2 = nextGradient.getFactor();
  56278. particle._currentDragGradient = currentGradient;
  56279. }
  56280. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56281. _this._scaledDirection.scaleInPlace(drag);
  56282. });
  56283. }
  56284. particle.position.addInPlace(_this._scaledDirection);
  56285. // Noise
  56286. if (noiseTextureData && noiseTextureSize) {
  56287. var localPosition = BABYLON.Tmp.Vector3[0];
  56288. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56289. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56290. particle.position.subtractToRef(emitterPosition, localPosition);
  56291. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56292. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56293. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56294. var force = BABYLON.Tmp.Vector3[0];
  56295. var scaledForce = BABYLON.Tmp.Vector3[1];
  56296. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56297. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56298. particle.direction.addInPlace(scaledForce);
  56299. }
  56300. // Gravity
  56301. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56302. particle.direction.addInPlace(_this._scaledGravity);
  56303. // Size
  56304. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56305. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56306. if (currentGradient !== particle._currentSizeGradient) {
  56307. particle._currentSize1 = particle._currentSize2;
  56308. particle._currentSize2 = nextGradient.getFactor();
  56309. particle._currentSizeGradient = currentGradient;
  56310. }
  56311. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56312. });
  56313. }
  56314. if (_this._isAnimationSheetEnabled) {
  56315. particle.updateCellIndex();
  56316. }
  56317. }
  56318. };
  56319. var particle;
  56320. for (var index = 0; index < particles.length; index++) {
  56321. _loop_1();
  56322. }
  56323. };
  56324. return _this;
  56325. }
  56326. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56327. /**
  56328. * Sets a callback that will be triggered when the system is disposed
  56329. */
  56330. set: function (callback) {
  56331. if (this._onDisposeObserver) {
  56332. this.onDisposeObservable.remove(this._onDisposeObserver);
  56333. }
  56334. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56335. },
  56336. enumerable: true,
  56337. configurable: true
  56338. });
  56339. /**
  56340. * Get hosting scene
  56341. * @returns the scene
  56342. */
  56343. ParticleSystem.prototype.getScene = function () {
  56344. return this._scene;
  56345. };
  56346. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56347. //end of Sub-emitter
  56348. /**
  56349. * Gets the current list of active particles
  56350. */
  56351. get: function () {
  56352. return this._particles;
  56353. },
  56354. enumerable: true,
  56355. configurable: true
  56356. });
  56357. /**
  56358. * Returns the string "ParticleSystem"
  56359. * @returns a string containing the class name
  56360. */
  56361. ParticleSystem.prototype.getClassName = function () {
  56362. return "ParticleSystem";
  56363. };
  56364. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56365. var newGradient = new BABYLON.FactorGradient();
  56366. newGradient.gradient = gradient;
  56367. newGradient.factor1 = factor;
  56368. newGradient.factor2 = factor2;
  56369. factorGradients.push(newGradient);
  56370. factorGradients.sort(function (a, b) {
  56371. if (a.gradient < b.gradient) {
  56372. return -1;
  56373. }
  56374. else if (a.gradient > b.gradient) {
  56375. return 1;
  56376. }
  56377. return 0;
  56378. });
  56379. };
  56380. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56381. if (!factorGradients) {
  56382. return;
  56383. }
  56384. var index = 0;
  56385. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56386. var factorGradient = factorGradients_1[_i];
  56387. if (factorGradient.gradient === gradient) {
  56388. factorGradients.splice(index, 1);
  56389. break;
  56390. }
  56391. index++;
  56392. }
  56393. };
  56394. /**
  56395. * Adds a new life time gradient
  56396. * @param gradient defines the gradient to use (between 0 and 1)
  56397. * @param factor defines the life time factor to affect to the specified gradient
  56398. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56399. * @returns the current particle system
  56400. */
  56401. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56402. if (!this._lifeTimeGradients) {
  56403. this._lifeTimeGradients = [];
  56404. }
  56405. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56406. return this;
  56407. };
  56408. /**
  56409. * Remove a specific life time gradient
  56410. * @param gradient defines the gradient to remove
  56411. * @returns the current particle system
  56412. */
  56413. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56414. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56415. return this;
  56416. };
  56417. /**
  56418. * Adds a new size gradient
  56419. * @param gradient defines the gradient to use (between 0 and 1)
  56420. * @param factor defines the size factor to affect to the specified gradient
  56421. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56422. * @returns the current particle system
  56423. */
  56424. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56425. if (!this._sizeGradients) {
  56426. this._sizeGradients = [];
  56427. }
  56428. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56429. return this;
  56430. };
  56431. /**
  56432. * Remove a specific size gradient
  56433. * @param gradient defines the gradient to remove
  56434. * @returns the current particle system
  56435. */
  56436. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56437. this._removeFactorGradient(this._sizeGradients, gradient);
  56438. return this;
  56439. };
  56440. /**
  56441. * Adds a new angular speed gradient
  56442. * @param gradient defines the gradient to use (between 0 and 1)
  56443. * @param factor defines the angular speed to affect to the specified gradient
  56444. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56445. * @returns the current particle system
  56446. */
  56447. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56448. if (!this._angularSpeedGradients) {
  56449. this._angularSpeedGradients = [];
  56450. }
  56451. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56452. return this;
  56453. };
  56454. /**
  56455. * Remove a specific angular speed gradient
  56456. * @param gradient defines the gradient to remove
  56457. * @returns the current particle system
  56458. */
  56459. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56460. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56461. return this;
  56462. };
  56463. /**
  56464. * Adds a new velocity gradient
  56465. * @param gradient defines the gradient to use (between 0 and 1)
  56466. * @param factor defines the velocity to affect to the specified gradient
  56467. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56468. * @returns the current particle system
  56469. */
  56470. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56471. if (!this._velocityGradients) {
  56472. this._velocityGradients = [];
  56473. }
  56474. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56475. return this;
  56476. };
  56477. /**
  56478. * Remove a specific velocity gradient
  56479. * @param gradient defines the gradient to remove
  56480. * @returns the current particle system
  56481. */
  56482. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56483. this._removeFactorGradient(this._velocityGradients, gradient);
  56484. return this;
  56485. };
  56486. /**
  56487. * Adds a new limit velocity gradient
  56488. * @param gradient defines the gradient to use (between 0 and 1)
  56489. * @param factor defines the limit velocity value to affect to the specified gradient
  56490. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56491. * @returns the current particle system
  56492. */
  56493. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56494. if (!this._limitVelocityGradients) {
  56495. this._limitVelocityGradients = [];
  56496. }
  56497. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56498. return this;
  56499. };
  56500. /**
  56501. * Remove a specific limit velocity gradient
  56502. * @param gradient defines the gradient to remove
  56503. * @returns the current particle system
  56504. */
  56505. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56506. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56507. return this;
  56508. };
  56509. /**
  56510. * Adds a new drag gradient
  56511. * @param gradient defines the gradient to use (between 0 and 1)
  56512. * @param factor defines the drag value to affect to the specified gradient
  56513. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56514. * @returns the current particle system
  56515. */
  56516. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56517. if (!this._dragGradients) {
  56518. this._dragGradients = [];
  56519. }
  56520. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56521. return this;
  56522. };
  56523. /**
  56524. * Remove a specific drag gradient
  56525. * @param gradient defines the gradient to remove
  56526. * @returns the current particle system
  56527. */
  56528. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56529. this._removeFactorGradient(this._dragGradients, gradient);
  56530. return this;
  56531. };
  56532. /**
  56533. * Adds a new color gradient
  56534. * @param gradient defines the gradient to use (between 0 and 1)
  56535. * @param color defines the color to affect to the specified gradient
  56536. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56537. */
  56538. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56539. if (!this._colorGradients) {
  56540. this._colorGradients = [];
  56541. }
  56542. var colorGradient = new BABYLON.ColorGradient();
  56543. colorGradient.gradient = gradient;
  56544. colorGradient.color1 = color;
  56545. colorGradient.color2 = color2;
  56546. this._colorGradients.push(colorGradient);
  56547. this._colorGradients.sort(function (a, b) {
  56548. if (a.gradient < b.gradient) {
  56549. return -1;
  56550. }
  56551. else if (a.gradient > b.gradient) {
  56552. return 1;
  56553. }
  56554. return 0;
  56555. });
  56556. return this;
  56557. };
  56558. /**
  56559. * Remove a specific color gradient
  56560. * @param gradient defines the gradient to remove
  56561. */
  56562. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56563. if (!this._colorGradients) {
  56564. return this;
  56565. }
  56566. var index = 0;
  56567. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56568. var colorGradient = _a[_i];
  56569. if (colorGradient.gradient === gradient) {
  56570. this._colorGradients.splice(index, 1);
  56571. break;
  56572. }
  56573. index++;
  56574. }
  56575. return this;
  56576. };
  56577. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56578. u = Math.abs(u) * 0.5 + 0.5;
  56579. v = Math.abs(v) * 0.5 + 0.5;
  56580. var wrappedU = ((u * width) % width) | 0;
  56581. var wrappedV = ((v * height) % height) | 0;
  56582. var position = (wrappedU + wrappedV * width) * 4;
  56583. return pixels[position] / 255;
  56584. };
  56585. ParticleSystem.prototype._reset = function () {
  56586. this._resetEffect();
  56587. };
  56588. ParticleSystem.prototype._resetEffect = function () {
  56589. if (this._vertexBuffer) {
  56590. this._vertexBuffer.dispose();
  56591. this._vertexBuffer = null;
  56592. }
  56593. if (this._spriteBuffer) {
  56594. this._spriteBuffer.dispose();
  56595. this._spriteBuffer = null;
  56596. }
  56597. this._createVertexBuffers();
  56598. };
  56599. ParticleSystem.prototype._createVertexBuffers = function () {
  56600. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56601. if (this._isAnimationSheetEnabled) {
  56602. this._vertexBufferSize += 1;
  56603. }
  56604. if (!this._isBillboardBased) {
  56605. this._vertexBufferSize += 3;
  56606. }
  56607. var engine = this._scene.getEngine();
  56608. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56609. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56610. var dataOffset = 0;
  56611. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56612. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56613. dataOffset += 3;
  56614. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56615. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56616. dataOffset += 4;
  56617. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56618. this._vertexBuffers["angle"] = options;
  56619. dataOffset += 1;
  56620. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56621. this._vertexBuffers["size"] = size;
  56622. dataOffset += 2;
  56623. if (this._isAnimationSheetEnabled) {
  56624. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56625. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56626. dataOffset += 1;
  56627. }
  56628. if (!this._isBillboardBased) {
  56629. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56630. this._vertexBuffers["direction"] = directionBuffer;
  56631. dataOffset += 3;
  56632. }
  56633. var offsets;
  56634. if (this._useInstancing) {
  56635. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56636. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56637. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56638. }
  56639. else {
  56640. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56641. dataOffset += 2;
  56642. }
  56643. this._vertexBuffers["offset"] = offsets;
  56644. };
  56645. ParticleSystem.prototype._createIndexBuffer = function () {
  56646. if (this._useInstancing) {
  56647. return;
  56648. }
  56649. var indices = [];
  56650. var index = 0;
  56651. for (var count = 0; count < this._capacity; count++) {
  56652. indices.push(index);
  56653. indices.push(index + 1);
  56654. indices.push(index + 2);
  56655. indices.push(index);
  56656. indices.push(index + 2);
  56657. indices.push(index + 3);
  56658. index += 4;
  56659. }
  56660. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56661. };
  56662. /**
  56663. * Gets the maximum number of particles active at the same time.
  56664. * @returns The max number of active particles.
  56665. */
  56666. ParticleSystem.prototype.getCapacity = function () {
  56667. return this._capacity;
  56668. };
  56669. /**
  56670. * Gets whether there are still active particles in the system.
  56671. * @returns True if it is alive, otherwise false.
  56672. */
  56673. ParticleSystem.prototype.isAlive = function () {
  56674. return this._alive;
  56675. };
  56676. /**
  56677. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56678. * @returns True if it has been started, otherwise false.
  56679. */
  56680. ParticleSystem.prototype.isStarted = function () {
  56681. return this._started;
  56682. };
  56683. /**
  56684. * Starts the particle system and begins to emit
  56685. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56686. */
  56687. ParticleSystem.prototype.start = function (delay) {
  56688. var _this = this;
  56689. if (delay === void 0) { delay = 0; }
  56690. if (delay) {
  56691. setTimeout(function () {
  56692. _this.start(0);
  56693. }, delay);
  56694. return;
  56695. }
  56696. this._started = true;
  56697. this._stopped = false;
  56698. this._actualFrame = 0;
  56699. if (this.subEmitters && this.subEmitters.length != 0) {
  56700. this.activeSubSystems = new Array();
  56701. }
  56702. if (this.preWarmCycles) {
  56703. for (var index = 0; index < this.preWarmCycles; index++) {
  56704. this.animate(true);
  56705. }
  56706. }
  56707. };
  56708. /**
  56709. * Stops the particle system.
  56710. * @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.
  56711. */
  56712. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56713. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56714. this._stopped = true;
  56715. if (stopSubEmitters) {
  56716. this._stopSubEmitters();
  56717. }
  56718. };
  56719. // animation sheet
  56720. /**
  56721. * Remove all active particles
  56722. */
  56723. ParticleSystem.prototype.reset = function () {
  56724. this._stockParticles = [];
  56725. this._particles = [];
  56726. };
  56727. /**
  56728. * @hidden (for internal use only)
  56729. */
  56730. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56731. var offset = index * this._vertexBufferSize;
  56732. this._vertexData[offset++] = particle.position.x;
  56733. this._vertexData[offset++] = particle.position.y;
  56734. this._vertexData[offset++] = particle.position.z;
  56735. this._vertexData[offset++] = particle.color.r;
  56736. this._vertexData[offset++] = particle.color.g;
  56737. this._vertexData[offset++] = particle.color.b;
  56738. this._vertexData[offset++] = particle.color.a;
  56739. this._vertexData[offset++] = particle.angle;
  56740. this._vertexData[offset++] = particle.scale.x * particle.size;
  56741. this._vertexData[offset++] = particle.scale.y * particle.size;
  56742. if (this._isAnimationSheetEnabled) {
  56743. this._vertexData[offset++] = particle.cellIndex;
  56744. }
  56745. if (!this._isBillboardBased) {
  56746. if (particle._initialDirection) {
  56747. this._vertexData[offset++] = particle._initialDirection.x;
  56748. this._vertexData[offset++] = particle._initialDirection.y;
  56749. this._vertexData[offset++] = particle._initialDirection.z;
  56750. }
  56751. else {
  56752. this._vertexData[offset++] = particle.direction.x;
  56753. this._vertexData[offset++] = particle.direction.y;
  56754. this._vertexData[offset++] = particle.direction.z;
  56755. }
  56756. }
  56757. if (!this._useInstancing) {
  56758. if (this._isAnimationSheetEnabled) {
  56759. if (offsetX === 0)
  56760. offsetX = this._epsilon;
  56761. else if (offsetX === 1)
  56762. offsetX = 1 - this._epsilon;
  56763. if (offsetY === 0)
  56764. offsetY = this._epsilon;
  56765. else if (offsetY === 1)
  56766. offsetY = 1 - this._epsilon;
  56767. }
  56768. this._vertexData[offset++] = offsetX;
  56769. this._vertexData[offset++] = offsetY;
  56770. }
  56771. };
  56772. ParticleSystem.prototype._stopSubEmitters = function () {
  56773. if (!this.activeSubSystems) {
  56774. return;
  56775. }
  56776. this.activeSubSystems.forEach(function (subSystem) {
  56777. subSystem.stop(true);
  56778. });
  56779. this.activeSubSystems = new Array();
  56780. };
  56781. ParticleSystem.prototype._removeFromRoot = function () {
  56782. if (!this._rootParticleSystem) {
  56783. return;
  56784. }
  56785. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56786. if (index !== -1) {
  56787. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56788. }
  56789. };
  56790. // End of sub system methods
  56791. ParticleSystem.prototype._update = function (newParticles) {
  56792. // Update current
  56793. this._alive = this._particles.length > 0;
  56794. if (this.emitter.position) {
  56795. var emitterMesh = this.emitter;
  56796. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56797. }
  56798. else {
  56799. var emitterPosition = this.emitter;
  56800. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56801. }
  56802. this.updateFunction(this._particles);
  56803. // Add new ones
  56804. var particle;
  56805. var _loop_2 = function () {
  56806. if (this_1._particles.length === this_1._capacity) {
  56807. return "break";
  56808. }
  56809. particle = this_1._createParticle();
  56810. this_1._particles.push(particle);
  56811. // Emitter
  56812. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56813. if (this_1.startPositionFunction) {
  56814. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56815. }
  56816. else {
  56817. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56818. }
  56819. if (this_1.startDirectionFunction) {
  56820. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56821. }
  56822. else {
  56823. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56824. }
  56825. if (emitPower === 0) {
  56826. if (!particle._initialDirection) {
  56827. particle._initialDirection = particle.direction.clone();
  56828. }
  56829. else {
  56830. particle._initialDirection.copyFrom(particle.direction);
  56831. }
  56832. }
  56833. else {
  56834. particle._initialDirection = null;
  56835. }
  56836. particle.direction.scaleInPlace(emitPower);
  56837. // Life time
  56838. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56839. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56840. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56841. var factorGradient1 = currentGradient;
  56842. var factorGradient2 = nextGradient;
  56843. var lifeTime1 = factorGradient1.getFactor();
  56844. var lifeTime2 = factorGradient2.getFactor();
  56845. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56846. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56847. });
  56848. }
  56849. else {
  56850. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56851. }
  56852. // Size
  56853. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56854. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56855. }
  56856. else {
  56857. particle._currentSizeGradient = this_1._sizeGradients[0];
  56858. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56859. particle.size = particle._currentSize1;
  56860. if (this_1._sizeGradients.length > 1) {
  56861. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56862. }
  56863. else {
  56864. particle._currentSize2 = particle._currentSize1;
  56865. }
  56866. }
  56867. // Size and scale
  56868. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56869. // Angle
  56870. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56871. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56872. }
  56873. else {
  56874. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56875. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56876. particle._currentAngularSpeed1 = particle.angularSpeed;
  56877. if (this_1._angularSpeedGradients.length > 1) {
  56878. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56879. }
  56880. else {
  56881. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56882. }
  56883. }
  56884. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56885. // Velocity
  56886. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56887. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56888. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56889. if (this_1._velocityGradients.length > 1) {
  56890. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56891. }
  56892. else {
  56893. particle._currentVelocity2 = particle._currentVelocity1;
  56894. }
  56895. }
  56896. // Limit velocity
  56897. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56898. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56899. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56900. if (this_1._limitVelocityGradients.length > 1) {
  56901. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56902. }
  56903. else {
  56904. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56905. }
  56906. }
  56907. // Drag
  56908. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  56909. particle._currentDragGradient = this_1._dragGradients[0];
  56910. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  56911. if (this_1._dragGradients.length > 1) {
  56912. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  56913. }
  56914. else {
  56915. particle._currentDrag2 = particle._currentDrag1;
  56916. }
  56917. }
  56918. // Color
  56919. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56920. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56921. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56922. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56923. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56924. }
  56925. else {
  56926. particle._currentColorGradient = this_1._colorGradients[0];
  56927. particle._currentColorGradient.getColorToRef(particle.color);
  56928. particle._currentColor1.copyFrom(particle.color);
  56929. if (this_1._colorGradients.length > 1) {
  56930. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56931. }
  56932. else {
  56933. particle._currentColor2.copyFrom(particle.color);
  56934. }
  56935. }
  56936. // Sheet
  56937. if (this_1._isAnimationSheetEnabled) {
  56938. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56939. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56940. }
  56941. };
  56942. var this_1 = this, step;
  56943. for (var index = 0; index < newParticles; index++) {
  56944. var state_1 = _loop_2();
  56945. if (state_1 === "break")
  56946. break;
  56947. }
  56948. };
  56949. /** @hidden */
  56950. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56951. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56952. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56953. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56954. if (isAnimationSheetEnabled) {
  56955. attributeNamesOrOptions.push("cellIndex");
  56956. }
  56957. if (!isBillboardBased) {
  56958. attributeNamesOrOptions.push("direction");
  56959. }
  56960. return attributeNamesOrOptions;
  56961. };
  56962. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56963. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56964. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  56965. if (isAnimationSheetEnabled) {
  56966. effectCreationOption.push("particlesInfos");
  56967. }
  56968. return effectCreationOption;
  56969. };
  56970. ParticleSystem.prototype._getEffect = function () {
  56971. if (this._customEffect) {
  56972. return this._customEffect;
  56973. }
  56974. ;
  56975. var defines = [];
  56976. if (this._scene.clipPlane) {
  56977. defines.push("#define CLIPPLANE");
  56978. }
  56979. if (this._scene.clipPlane2) {
  56980. defines.push("#define CLIPPLANE2");
  56981. }
  56982. if (this._scene.clipPlane3) {
  56983. defines.push("#define CLIPPLANE3");
  56984. }
  56985. if (this._scene.clipPlane4) {
  56986. defines.push("#define CLIPPLANE4");
  56987. }
  56988. if (this._isAnimationSheetEnabled) {
  56989. defines.push("#define ANIMATESHEET");
  56990. }
  56991. if (this._isBillboardBased) {
  56992. defines.push("#define BILLBOARD");
  56993. switch (this.billboardMode) {
  56994. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56995. defines.push("#define BILLBOARDY");
  56996. break;
  56997. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56998. default:
  56999. break;
  57000. }
  57001. }
  57002. if (this._imageProcessingConfiguration) {
  57003. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57004. defines.push(this._imageProcessingConfigurationDefines.toString());
  57005. }
  57006. // Effect
  57007. var join = defines.join("\n");
  57008. if (this._cachedDefines !== join) {
  57009. this._cachedDefines = join;
  57010. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  57011. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57012. var samplers = ["diffuseSampler"];
  57013. if (BABYLON.ImageProcessingConfiguration) {
  57014. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57015. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57016. }
  57017. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  57018. }
  57019. return this._effect;
  57020. };
  57021. /**
  57022. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57023. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57024. */
  57025. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57026. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57027. if (!this._started)
  57028. return;
  57029. if (!preWarmOnly) {
  57030. var effect = this._getEffect();
  57031. // Check
  57032. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57033. return;
  57034. if (this._currentRenderId === this._scene.getRenderId()) {
  57035. return;
  57036. }
  57037. this._currentRenderId = this._scene.getRenderId();
  57038. }
  57039. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57040. // determine the number of particles we need to create
  57041. var newParticles;
  57042. if (this.manualEmitCount > -1) {
  57043. newParticles = this.manualEmitCount;
  57044. this._newPartsExcess = 0;
  57045. this.manualEmitCount = 0;
  57046. }
  57047. else {
  57048. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  57049. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  57050. }
  57051. if (this._newPartsExcess > 1.0) {
  57052. newParticles += this._newPartsExcess >> 0;
  57053. this._newPartsExcess -= this._newPartsExcess >> 0;
  57054. }
  57055. this._alive = false;
  57056. if (!this._stopped) {
  57057. this._actualFrame += this._scaledUpdateSpeed;
  57058. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57059. this.stop();
  57060. }
  57061. else {
  57062. newParticles = 0;
  57063. }
  57064. this._update(newParticles);
  57065. // Stopped?
  57066. if (this._stopped) {
  57067. if (!this._alive) {
  57068. this._started = false;
  57069. if (this.onAnimationEnd) {
  57070. this.onAnimationEnd();
  57071. }
  57072. if (this.disposeOnStop) {
  57073. this._scene._toBeDisposed.push(this);
  57074. }
  57075. }
  57076. }
  57077. if (!preWarmOnly) {
  57078. // Update VBO
  57079. var offset = 0;
  57080. for (var index = 0; index < this._particles.length; index++) {
  57081. var particle = this._particles[index];
  57082. this._appendParticleVertices(offset, particle);
  57083. offset += this._useInstancing ? 1 : 4;
  57084. }
  57085. if (this._vertexBuffer) {
  57086. this._vertexBuffer.update(this._vertexData);
  57087. }
  57088. }
  57089. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57090. this.stop();
  57091. }
  57092. };
  57093. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57094. this._appendParticleVertex(offset++, particle, 0, 0);
  57095. if (!this._useInstancing) {
  57096. this._appendParticleVertex(offset++, particle, 1, 0);
  57097. this._appendParticleVertex(offset++, particle, 1, 1);
  57098. this._appendParticleVertex(offset++, particle, 0, 1);
  57099. }
  57100. };
  57101. /**
  57102. * Rebuilds the particle system.
  57103. */
  57104. ParticleSystem.prototype.rebuild = function () {
  57105. this._createIndexBuffer();
  57106. if (this._vertexBuffer) {
  57107. this._vertexBuffer._rebuild();
  57108. }
  57109. };
  57110. /**
  57111. * Is this system ready to be used/rendered
  57112. * @return true if the system is ready
  57113. */
  57114. ParticleSystem.prototype.isReady = function () {
  57115. var effect = this._getEffect();
  57116. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57117. return false;
  57118. }
  57119. return true;
  57120. };
  57121. /**
  57122. * Renders the particle system in its current state.
  57123. * @returns the current number of particles
  57124. */
  57125. ParticleSystem.prototype.render = function () {
  57126. var effect = this._getEffect();
  57127. // Check
  57128. if (!this.isReady() || !this._particles.length) {
  57129. return 0;
  57130. }
  57131. var engine = this._scene.getEngine();
  57132. // Render
  57133. engine.enableEffect(effect);
  57134. engine.setState(false);
  57135. var viewMatrix = this._scene.getViewMatrix();
  57136. effect.setTexture("diffuseSampler", this.particleTexture);
  57137. effect.setMatrix("view", viewMatrix);
  57138. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57139. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57140. var baseSize = this.particleTexture.getBaseSize();
  57141. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57142. }
  57143. effect.setVector2("translationPivot", this.translationPivot);
  57144. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57145. if (this._isBillboardBased) {
  57146. var camera = this._scene.activeCamera;
  57147. effect.setVector3("eyePosition", camera.globalPosition);
  57148. }
  57149. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57150. var invView = viewMatrix.clone();
  57151. invView.invert();
  57152. effect.setMatrix("invView", invView);
  57153. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57154. }
  57155. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57156. // image processing
  57157. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57158. this._imageProcessingConfiguration.bind(effect);
  57159. }
  57160. // Draw order
  57161. switch (this.blendMode) {
  57162. case ParticleSystem.BLENDMODE_ADD:
  57163. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57164. break;
  57165. case ParticleSystem.BLENDMODE_ONEONE:
  57166. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57167. break;
  57168. case ParticleSystem.BLENDMODE_STANDARD:
  57169. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57170. break;
  57171. }
  57172. if (this.forceDepthWrite) {
  57173. engine.setDepthWrite(true);
  57174. }
  57175. if (this._useInstancing) {
  57176. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57177. engine.unbindInstanceAttributes();
  57178. }
  57179. else {
  57180. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57181. }
  57182. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57183. return this._particles.length;
  57184. };
  57185. /**
  57186. * Disposes the particle system and free the associated resources
  57187. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57188. */
  57189. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57190. if (disposeTexture === void 0) { disposeTexture = true; }
  57191. if (this._vertexBuffer) {
  57192. this._vertexBuffer.dispose();
  57193. this._vertexBuffer = null;
  57194. }
  57195. if (this._spriteBuffer) {
  57196. this._spriteBuffer.dispose();
  57197. this._spriteBuffer = null;
  57198. }
  57199. if (this._indexBuffer) {
  57200. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57201. this._indexBuffer = null;
  57202. }
  57203. if (disposeTexture && this.particleTexture) {
  57204. this.particleTexture.dispose();
  57205. this.particleTexture = null;
  57206. }
  57207. if (disposeTexture && this.noiseTexture) {
  57208. this.noiseTexture.dispose();
  57209. this.noiseTexture = null;
  57210. }
  57211. this._removeFromRoot();
  57212. // Remove from scene
  57213. var index = this._scene.particleSystems.indexOf(this);
  57214. if (index > -1) {
  57215. this._scene.particleSystems.splice(index, 1);
  57216. }
  57217. // Callback
  57218. this.onDisposeObservable.notifyObservers(this);
  57219. this.onDisposeObservable.clear();
  57220. };
  57221. // Clone
  57222. /**
  57223. * Clones the particle system.
  57224. * @param name The name of the cloned object
  57225. * @param newEmitter The new emitter to use
  57226. * @returns the cloned particle system
  57227. */
  57228. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57229. var custom = null;
  57230. var program = null;
  57231. if (this.customShader != null) {
  57232. program = this.customShader;
  57233. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57234. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57235. }
  57236. else if (this._customEffect) {
  57237. custom = this._customEffect;
  57238. }
  57239. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57240. result.customShader = program;
  57241. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57242. if (newEmitter === undefined) {
  57243. newEmitter = this.emitter;
  57244. }
  57245. result.emitter = newEmitter;
  57246. if (this.particleTexture) {
  57247. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57248. }
  57249. if (!this.preventAutoStart) {
  57250. result.start();
  57251. }
  57252. return result;
  57253. };
  57254. /**
  57255. * Serializes the particle system to a JSON object.
  57256. * @returns the JSON object
  57257. */
  57258. ParticleSystem.prototype.serialize = function () {
  57259. var serializationObject = {};
  57260. ParticleSystem._Serialize(serializationObject, this);
  57261. serializationObject.textureMask = this.textureMask.asArray();
  57262. serializationObject.customShader = this.customShader;
  57263. serializationObject.preventAutoStart = this.preventAutoStart;
  57264. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57265. return serializationObject;
  57266. };
  57267. /** @hidden */
  57268. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57269. serializationObject.name = particleSystem.name;
  57270. serializationObject.id = particleSystem.id;
  57271. serializationObject.capacity = particleSystem.getCapacity();
  57272. // Emitter
  57273. if (particleSystem.emitter.position) {
  57274. var emitterMesh = particleSystem.emitter;
  57275. serializationObject.emitterId = emitterMesh.id;
  57276. }
  57277. else {
  57278. var emitterPosition = particleSystem.emitter;
  57279. serializationObject.emitter = emitterPosition.asArray();
  57280. }
  57281. // Emitter
  57282. if (particleSystem.particleEmitterType) {
  57283. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57284. }
  57285. if (particleSystem.particleTexture) {
  57286. serializationObject.textureName = particleSystem.particleTexture.name;
  57287. }
  57288. // Animations
  57289. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57290. // Particle system
  57291. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57292. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57293. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57294. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57295. serializationObject.minSize = particleSystem.minSize;
  57296. serializationObject.maxSize = particleSystem.maxSize;
  57297. serializationObject.minScaleX = particleSystem.minScaleX;
  57298. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57299. serializationObject.minScaleY = particleSystem.minScaleY;
  57300. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57301. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57302. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57303. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57304. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57305. serializationObject.emitRate = particleSystem.emitRate;
  57306. serializationObject.gravity = particleSystem.gravity.asArray();
  57307. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57308. serializationObject.color1 = particleSystem.color1.asArray();
  57309. serializationObject.color2 = particleSystem.color2.asArray();
  57310. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57311. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57312. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57313. serializationObject.blendMode = particleSystem.blendMode;
  57314. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57315. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57316. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57317. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57318. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57319. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57320. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57321. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57322. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57323. var colorGradients = particleSystem.getColorGradients();
  57324. if (colorGradients) {
  57325. serializationObject.colorGradients = [];
  57326. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57327. var colorGradient = colorGradients_1[_i];
  57328. var serializedGradient = {
  57329. gradient: colorGradient.gradient,
  57330. color1: colorGradient.color1.asArray()
  57331. };
  57332. if (colorGradient.color2) {
  57333. serializedGradient.color2 = colorGradient.color2.asArray();
  57334. }
  57335. serializationObject.colorGradients.push(serializedGradient);
  57336. }
  57337. }
  57338. var sizeGradients = particleSystem.getSizeGradients();
  57339. if (sizeGradients) {
  57340. serializationObject.sizeGradients = [];
  57341. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57342. var sizeGradient = sizeGradients_1[_a];
  57343. var serializedGradient = {
  57344. gradient: sizeGradient.gradient,
  57345. factor1: sizeGradient.factor1
  57346. };
  57347. if (sizeGradient.factor2 !== undefined) {
  57348. serializedGradient.factor2 = sizeGradient.factor2;
  57349. }
  57350. serializationObject.sizeGradients.push(serializedGradient);
  57351. }
  57352. }
  57353. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57354. if (angularSpeedGradients) {
  57355. serializationObject.angularSpeedGradients = [];
  57356. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57357. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57358. var serializedGradient = {
  57359. gradient: angularSpeedGradient.gradient,
  57360. factor1: angularSpeedGradient.factor1
  57361. };
  57362. if (angularSpeedGradient.factor2 !== undefined) {
  57363. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57364. }
  57365. serializationObject.angularSpeedGradients.push(serializedGradient);
  57366. }
  57367. }
  57368. var velocityGradients = particleSystem.getVelocityGradients();
  57369. if (velocityGradients) {
  57370. serializationObject.velocityGradients = [];
  57371. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57372. var velocityGradient = velocityGradients_1[_c];
  57373. var serializedGradient = {
  57374. gradient: velocityGradient.gradient,
  57375. factor1: velocityGradient.factor1
  57376. };
  57377. if (velocityGradient.factor2 !== undefined) {
  57378. serializedGradient.factor2 = velocityGradient.factor2;
  57379. }
  57380. serializationObject.velocityGradients.push(serializedGradient);
  57381. }
  57382. }
  57383. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57384. if (limitVelocityGradients) {
  57385. serializationObject.limitVelocityGradients = [];
  57386. for (var _d = 0, limitVelocityGradients_1 = limitVelocityGradients; _d < limitVelocityGradients_1.length; _d++) {
  57387. var limitVelocityGradient = limitVelocityGradients_1[_d];
  57388. var serializedGradient = {
  57389. gradient: limitVelocityGradient.gradient,
  57390. factor1: limitVelocityGradient.factor1
  57391. };
  57392. if (limitVelocityGradient.factor2 !== undefined) {
  57393. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57394. }
  57395. serializationObject.limitVelocityGradients.push(serializedGradient);
  57396. }
  57397. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57398. }
  57399. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57400. var noiseTexture = particleSystem.noiseTexture;
  57401. serializationObject.noiseTexture = noiseTexture.serialize();
  57402. }
  57403. };
  57404. /** @hidden */
  57405. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57406. // Texture
  57407. if (parsedParticleSystem.textureName) {
  57408. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57409. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57410. }
  57411. // Emitter
  57412. if (parsedParticleSystem.emitterId === undefined) {
  57413. particleSystem.emitter = BABYLON.Vector3.Zero();
  57414. }
  57415. else if (parsedParticleSystem.emitterId) {
  57416. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57417. }
  57418. else {
  57419. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57420. }
  57421. // Misc.
  57422. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57423. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57424. }
  57425. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57426. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57427. }
  57428. // Animations
  57429. if (parsedParticleSystem.animations) {
  57430. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57431. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57432. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57433. }
  57434. }
  57435. if (parsedParticleSystem.autoAnimate) {
  57436. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57437. }
  57438. // Particle system
  57439. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57440. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57441. particleSystem.minSize = parsedParticleSystem.minSize;
  57442. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57443. if (parsedParticleSystem.minScaleX) {
  57444. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57445. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57446. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57447. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57448. }
  57449. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57450. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57451. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57452. }
  57453. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57454. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57455. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57456. }
  57457. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57458. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57459. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57460. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57461. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57462. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57463. if (parsedParticleSystem.noiseStrength) {
  57464. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57465. }
  57466. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57467. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57468. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57469. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57470. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57471. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57472. if (parsedParticleSystem.colorGradients) {
  57473. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57474. var colorGradient = _a[_i];
  57475. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57476. }
  57477. }
  57478. if (parsedParticleSystem.sizeGradients) {
  57479. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57480. var sizeGradient = _c[_b];
  57481. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57482. }
  57483. }
  57484. if (parsedParticleSystem.angularSpeedGradients) {
  57485. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57486. var angularSpeedGradient = _e[_d];
  57487. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57488. }
  57489. }
  57490. if (parsedParticleSystem.velocityGradients) {
  57491. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57492. var velocityGradient = _g[_f];
  57493. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57494. }
  57495. }
  57496. if (parsedParticleSystem.limitVelocityGradients) {
  57497. for (var _h = 0, _j = parsedParticleSystem.limitVelocityGradients; _h < _j.length; _h++) {
  57498. var limitVelocityGradient = _j[_h];
  57499. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57500. }
  57501. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57502. }
  57503. if (parsedParticleSystem.noiseTexture) {
  57504. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57505. }
  57506. // Emitter
  57507. var emitterType;
  57508. if (parsedParticleSystem.particleEmitterType) {
  57509. switch (parsedParticleSystem.particleEmitterType.type) {
  57510. case "SphereParticleEmitter":
  57511. emitterType = new BABYLON.SphereParticleEmitter();
  57512. break;
  57513. case "SphereDirectedParticleEmitter":
  57514. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57515. break;
  57516. case "ConeEmitter":
  57517. case "ConeParticleEmitter":
  57518. emitterType = new BABYLON.ConeParticleEmitter();
  57519. break;
  57520. case "BoxEmitter":
  57521. case "BoxParticleEmitter":
  57522. default:
  57523. emitterType = new BABYLON.BoxParticleEmitter();
  57524. break;
  57525. }
  57526. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57527. }
  57528. else {
  57529. emitterType = new BABYLON.BoxParticleEmitter();
  57530. emitterType.parse(parsedParticleSystem);
  57531. }
  57532. particleSystem.particleEmitterType = emitterType;
  57533. // Animation sheet
  57534. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57535. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57536. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57537. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57538. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57539. };
  57540. /**
  57541. * Parses a JSON object to create a particle system.
  57542. * @param parsedParticleSystem The JSON object to parse
  57543. * @param scene The scene to create the particle system in
  57544. * @param rootUrl The root url to use to load external dependencies like texture
  57545. * @returns the Parsed particle system
  57546. */
  57547. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57548. var name = parsedParticleSystem.name;
  57549. var custom = null;
  57550. var program = null;
  57551. if (parsedParticleSystem.customShader) {
  57552. program = parsedParticleSystem.customShader;
  57553. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57554. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57555. }
  57556. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57557. particleSystem.customShader = program;
  57558. if (parsedParticleSystem.id) {
  57559. particleSystem.id = parsedParticleSystem.id;
  57560. }
  57561. // Auto start
  57562. if (parsedParticleSystem.preventAutoStart) {
  57563. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57564. }
  57565. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57566. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57567. if (!particleSystem.preventAutoStart) {
  57568. particleSystem.start();
  57569. }
  57570. return particleSystem;
  57571. };
  57572. return ParticleSystem;
  57573. }(BABYLON.BaseParticleSystem));
  57574. BABYLON.ParticleSystem = ParticleSystem;
  57575. })(BABYLON || (BABYLON = {}));
  57576. //# sourceMappingURL=babylon.particleSystem.js.map
  57577. var BABYLON;
  57578. (function (BABYLON) {
  57579. /**
  57580. * Particle emitter emitting particles from the inside of a box.
  57581. * It emits the particles randomly between 2 given directions.
  57582. */
  57583. var BoxParticleEmitter = /** @class */ (function () {
  57584. /**
  57585. * Creates a new instance BoxParticleEmitter
  57586. */
  57587. function BoxParticleEmitter() {
  57588. /**
  57589. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57590. */
  57591. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57592. /**
  57593. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57594. */
  57595. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57596. /**
  57597. * 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.
  57598. */
  57599. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57600. /**
  57601. * 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.
  57602. */
  57603. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57604. }
  57605. /**
  57606. * Called by the particle System when the direction is computed for the created particle.
  57607. * @param worldMatrix is the world matrix of the particle system
  57608. * @param directionToUpdate is the direction vector to update with the result
  57609. * @param particle is the particle we are computed the direction for
  57610. */
  57611. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57612. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57613. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57614. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57615. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57616. };
  57617. /**
  57618. * Called by the particle System when the position is computed for the created particle.
  57619. * @param worldMatrix is the world matrix of the particle system
  57620. * @param positionToUpdate is the position vector to update with the result
  57621. * @param particle is the particle we are computed the position for
  57622. */
  57623. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57624. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57625. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57626. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57627. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57628. };
  57629. /**
  57630. * Clones the current emitter and returns a copy of it
  57631. * @returns the new emitter
  57632. */
  57633. BoxParticleEmitter.prototype.clone = function () {
  57634. var newOne = new BoxParticleEmitter();
  57635. BABYLON.Tools.DeepCopy(this, newOne);
  57636. return newOne;
  57637. };
  57638. /**
  57639. * Called by the GPUParticleSystem to setup the update shader
  57640. * @param effect defines the update shader
  57641. */
  57642. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57643. effect.setVector3("direction1", this.direction1);
  57644. effect.setVector3("direction2", this.direction2);
  57645. effect.setVector3("minEmitBox", this.minEmitBox);
  57646. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57647. };
  57648. /**
  57649. * Returns a string to use to update the GPU particles update shader
  57650. * @returns a string containng the defines string
  57651. */
  57652. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57653. return "#define BOXEMITTER";
  57654. };
  57655. /**
  57656. * Returns the string "BoxParticleEmitter"
  57657. * @returns a string containing the class name
  57658. */
  57659. BoxParticleEmitter.prototype.getClassName = function () {
  57660. return "BoxParticleEmitter";
  57661. };
  57662. /**
  57663. * Serializes the particle system to a JSON object.
  57664. * @returns the JSON object
  57665. */
  57666. BoxParticleEmitter.prototype.serialize = function () {
  57667. var serializationObject = {};
  57668. serializationObject.type = this.getClassName();
  57669. serializationObject.direction1 = this.direction1.asArray();
  57670. serializationObject.direction2 = this.direction2.asArray();
  57671. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57672. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57673. return serializationObject;
  57674. };
  57675. /**
  57676. * Parse properties from a JSON object
  57677. * @param serializationObject defines the JSON object
  57678. */
  57679. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57680. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57681. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57682. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57683. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57684. };
  57685. return BoxParticleEmitter;
  57686. }());
  57687. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57688. })(BABYLON || (BABYLON = {}));
  57689. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57690. var BABYLON;
  57691. (function (BABYLON) {
  57692. /**
  57693. * Particle emitter emitting particles from the inside of a cylinder.
  57694. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  57695. */
  57696. var CylinderParticleEmitter = /** @class */ (function () {
  57697. /**
  57698. * Creates a new instance CylinderParticleEmitter
  57699. * @param radius the radius of the emission cylinder (1 by default)
  57700. * @param height the height of the emission cylinder (1 by default)
  57701. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57702. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57703. */
  57704. function CylinderParticleEmitter(
  57705. /**
  57706. * The radius of the emission cylinder.
  57707. */
  57708. radius,
  57709. /**
  57710. * The height of the emission cylinder.
  57711. */
  57712. height,
  57713. /**
  57714. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57715. */
  57716. radiusRange,
  57717. /**
  57718. * How much to randomize the particle direction [0-1].
  57719. */
  57720. directionRandomizer) {
  57721. if (radius === void 0) { radius = 1; }
  57722. if (height === void 0) { height = 1; }
  57723. if (radiusRange === void 0) { radiusRange = 1; }
  57724. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57725. this.radius = radius;
  57726. this.height = height;
  57727. this.radiusRange = radiusRange;
  57728. this.directionRandomizer = directionRandomizer;
  57729. }
  57730. /**
  57731. * Called by the particle System when the direction is computed for the created particle.
  57732. * @param worldMatrix is the world matrix of the particle system
  57733. * @param directionToUpdate is the direction vector to update with the result
  57734. * @param particle is the particle we are computed the direction for
  57735. */
  57736. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57737. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57738. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  57739. var angle = Math.atan2(direction.x, direction.z);
  57740. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  57741. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  57742. direction.x = Math.sin(angle);
  57743. direction.z = Math.cos(angle);
  57744. direction.normalize();
  57745. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57746. };
  57747. /**
  57748. * Called by the particle System when the position is computed for the created particle.
  57749. * @param worldMatrix is the world matrix of the particle system
  57750. * @param positionToUpdate is the position vector to update with the result
  57751. * @param particle is the particle we are computed the position for
  57752. */
  57753. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57754. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  57755. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57756. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  57757. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  57758. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  57759. var xPos = positionRadius * Math.cos(angle);
  57760. var zPos = positionRadius * Math.sin(angle);
  57761. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  57762. };
  57763. /**
  57764. * Clones the current emitter and returns a copy of it
  57765. * @returns the new emitter
  57766. */
  57767. CylinderParticleEmitter.prototype.clone = function () {
  57768. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  57769. BABYLON.Tools.DeepCopy(this, newOne);
  57770. return newOne;
  57771. };
  57772. /**
  57773. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57774. * @param effect defines the update shader
  57775. */
  57776. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  57777. effect.setFloat("radius", this.radius);
  57778. effect.setFloat("height", this.height);
  57779. effect.setFloat("radiusRange", this.radiusRange);
  57780. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57781. };
  57782. /**
  57783. * Returns a string to use to update the GPU particles update shader
  57784. * @returns a string containng the defines string
  57785. */
  57786. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  57787. return "#define CYLINDEREMITTER";
  57788. };
  57789. /**
  57790. * Returns the string "CylinderParticleEmitter"
  57791. * @returns a string containing the class name
  57792. */
  57793. CylinderParticleEmitter.prototype.getClassName = function () {
  57794. return "CylinderParticleEmitter";
  57795. };
  57796. /**
  57797. * Serializes the particle system to a JSON object.
  57798. * @returns the JSON object
  57799. */
  57800. CylinderParticleEmitter.prototype.serialize = function () {
  57801. var serializationObject = {};
  57802. serializationObject.type = this.getClassName();
  57803. serializationObject.radius = this.radius;
  57804. serializationObject.height = this.height;
  57805. serializationObject.radiusRange = this.radiusRange;
  57806. serializationObject.directionRandomizer = this.directionRandomizer;
  57807. return serializationObject;
  57808. };
  57809. /**
  57810. * Parse properties from a JSON object
  57811. * @param serializationObject defines the JSON object
  57812. */
  57813. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  57814. this.radius = serializationObject.radius;
  57815. this.height = serializationObject.height;
  57816. this.radiusRange = serializationObject.radiusRange;
  57817. this.directionRandomizer = serializationObject.directionRandomizer;
  57818. };
  57819. return CylinderParticleEmitter;
  57820. }());
  57821. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  57822. })(BABYLON || (BABYLON = {}));
  57823. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  57824. var BABYLON;
  57825. (function (BABYLON) {
  57826. /**
  57827. * Particle emitter emitting particles from the inside of a cone.
  57828. * It emits the particles alongside the cone volume from the base to the particle.
  57829. * The emission direction might be randomized.
  57830. */
  57831. var ConeParticleEmitter = /** @class */ (function () {
  57832. /**
  57833. * Creates a new instance ConeParticleEmitter
  57834. * @param radius the radius of the emission cone (1 by default)
  57835. * @param angles the cone base angle (PI by default)
  57836. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57837. */
  57838. function ConeParticleEmitter(radius, angle,
  57839. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57840. directionRandomizer) {
  57841. if (radius === void 0) { radius = 1; }
  57842. if (angle === void 0) { angle = Math.PI; }
  57843. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57844. this.directionRandomizer = directionRandomizer;
  57845. /**
  57846. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57847. */
  57848. this.radiusRange = 1;
  57849. /**
  57850. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57851. */
  57852. this.heightRange = 1;
  57853. /**
  57854. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57855. */
  57856. this.emitFromSpawnPointOnly = false;
  57857. this.angle = angle;
  57858. this.radius = radius;
  57859. }
  57860. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57861. /**
  57862. * Gets or sets the radius of the emission cone
  57863. */
  57864. get: function () {
  57865. return this._radius;
  57866. },
  57867. set: function (value) {
  57868. this._radius = value;
  57869. this._buildHeight();
  57870. },
  57871. enumerable: true,
  57872. configurable: true
  57873. });
  57874. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57875. /**
  57876. * Gets or sets the angle of the emission cone
  57877. */
  57878. get: function () {
  57879. return this._angle;
  57880. },
  57881. set: function (value) {
  57882. this._angle = value;
  57883. this._buildHeight();
  57884. },
  57885. enumerable: true,
  57886. configurable: true
  57887. });
  57888. ConeParticleEmitter.prototype._buildHeight = function () {
  57889. if (this._angle !== 0) {
  57890. this._height = this._radius / Math.tan(this._angle / 2);
  57891. }
  57892. else {
  57893. this._height = 1;
  57894. }
  57895. };
  57896. /**
  57897. * Called by the particle System when the direction is computed for the created particle.
  57898. * @param worldMatrix is the world matrix of the particle system
  57899. * @param directionToUpdate is the direction vector to update with the result
  57900. * @param particle is the particle we are computed the direction for
  57901. */
  57902. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57903. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57904. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57905. }
  57906. else {
  57907. // measure the direction Vector from the emitter to the particle.
  57908. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57909. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57910. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57911. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57912. direction.x += randX;
  57913. direction.y += randY;
  57914. direction.z += randZ;
  57915. direction.normalize();
  57916. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57917. }
  57918. };
  57919. /**
  57920. * Called by the particle System when the position is computed for the created particle.
  57921. * @param worldMatrix is the world matrix of the particle system
  57922. * @param positionToUpdate is the position vector to update with the result
  57923. * @param particle is the particle we are computed the position for
  57924. */
  57925. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57926. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57927. var h;
  57928. if (!this.emitFromSpawnPointOnly) {
  57929. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57930. // Better distribution in a cone at normal angles.
  57931. h = 1 - h * h;
  57932. }
  57933. else {
  57934. h = 0.0001;
  57935. }
  57936. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57937. radius = radius * h;
  57938. var randX = radius * Math.sin(s);
  57939. var randZ = radius * Math.cos(s);
  57940. var randY = h * this._height;
  57941. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57942. };
  57943. /**
  57944. * Clones the current emitter and returns a copy of it
  57945. * @returns the new emitter
  57946. */
  57947. ConeParticleEmitter.prototype.clone = function () {
  57948. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57949. BABYLON.Tools.DeepCopy(this, newOne);
  57950. return newOne;
  57951. };
  57952. /**
  57953. * Called by the GPUParticleSystem to setup the update shader
  57954. * @param effect defines the update shader
  57955. */
  57956. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57957. effect.setFloat2("radius", this._radius, this.radiusRange);
  57958. effect.setFloat("coneAngle", this._angle);
  57959. effect.setFloat2("height", this._height, this.heightRange);
  57960. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57961. };
  57962. /**
  57963. * Returns a string to use to update the GPU particles update shader
  57964. * @returns a string containng the defines string
  57965. */
  57966. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57967. var defines = "#define CONEEMITTER";
  57968. if (this.emitFromSpawnPointOnly) {
  57969. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57970. }
  57971. return defines;
  57972. };
  57973. /**
  57974. * Returns the string "ConeParticleEmitter"
  57975. * @returns a string containing the class name
  57976. */
  57977. ConeParticleEmitter.prototype.getClassName = function () {
  57978. return "ConeParticleEmitter";
  57979. };
  57980. /**
  57981. * Serializes the particle system to a JSON object.
  57982. * @returns the JSON object
  57983. */
  57984. ConeParticleEmitter.prototype.serialize = function () {
  57985. var serializationObject = {};
  57986. serializationObject.type = this.getClassName();
  57987. serializationObject.radius = this._radius;
  57988. serializationObject.angle = this._angle;
  57989. serializationObject.directionRandomizer = this.directionRandomizer;
  57990. return serializationObject;
  57991. };
  57992. /**
  57993. * Parse properties from a JSON object
  57994. * @param serializationObject defines the JSON object
  57995. */
  57996. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57997. this.radius = serializationObject.radius;
  57998. this.angle = serializationObject.angle;
  57999. this.directionRandomizer = serializationObject.directionRandomizer;
  58000. };
  58001. return ConeParticleEmitter;
  58002. }());
  58003. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58004. })(BABYLON || (BABYLON = {}));
  58005. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58006. var BABYLON;
  58007. (function (BABYLON) {
  58008. /**
  58009. * Particle emitter emitting particles from the inside of a sphere.
  58010. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58011. */
  58012. var SphereParticleEmitter = /** @class */ (function () {
  58013. /**
  58014. * Creates a new instance SphereParticleEmitter
  58015. * @param radius the radius of the emission sphere (1 by default)
  58016. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58017. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58018. */
  58019. function SphereParticleEmitter(
  58020. /**
  58021. * The radius of the emission sphere.
  58022. */
  58023. radius,
  58024. /**
  58025. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58026. */
  58027. radiusRange,
  58028. /**
  58029. * How much to randomize the particle direction [0-1].
  58030. */
  58031. directionRandomizer) {
  58032. if (radius === void 0) { radius = 1; }
  58033. if (radiusRange === void 0) { radiusRange = 1; }
  58034. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58035. this.radius = radius;
  58036. this.radiusRange = radiusRange;
  58037. this.directionRandomizer = directionRandomizer;
  58038. }
  58039. /**
  58040. * Called by the particle System when the direction is computed for the created particle.
  58041. * @param worldMatrix is the world matrix of the particle system
  58042. * @param directionToUpdate is the direction vector to update with the result
  58043. * @param particle is the particle we are computed the direction for
  58044. */
  58045. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58046. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58047. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58048. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58049. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58050. direction.x += randX;
  58051. direction.y += randY;
  58052. direction.z += randZ;
  58053. direction.normalize();
  58054. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58055. };
  58056. /**
  58057. * Called by the particle System when the position is computed for the created particle.
  58058. * @param worldMatrix is the world matrix of the particle system
  58059. * @param positionToUpdate is the position vector to update with the result
  58060. * @param particle is the particle we are computed the position for
  58061. */
  58062. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58063. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58064. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58065. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58066. var theta = Math.acos(2 * v - 1);
  58067. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58068. var randY = randRadius * Math.cos(theta);
  58069. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58070. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58071. };
  58072. /**
  58073. * Clones the current emitter and returns a copy of it
  58074. * @returns the new emitter
  58075. */
  58076. SphereParticleEmitter.prototype.clone = function () {
  58077. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58078. BABYLON.Tools.DeepCopy(this, newOne);
  58079. return newOne;
  58080. };
  58081. /**
  58082. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58083. * @param effect defines the update shader
  58084. */
  58085. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58086. effect.setFloat("radius", this.radius);
  58087. effect.setFloat("radiusRange", this.radiusRange);
  58088. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58089. };
  58090. /**
  58091. * Returns a string to use to update the GPU particles update shader
  58092. * @returns a string containng the defines string
  58093. */
  58094. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58095. return "#define SPHEREEMITTER";
  58096. };
  58097. /**
  58098. * Returns the string "SphereParticleEmitter"
  58099. * @returns a string containing the class name
  58100. */
  58101. SphereParticleEmitter.prototype.getClassName = function () {
  58102. return "SphereParticleEmitter";
  58103. };
  58104. /**
  58105. * Serializes the particle system to a JSON object.
  58106. * @returns the JSON object
  58107. */
  58108. SphereParticleEmitter.prototype.serialize = function () {
  58109. var serializationObject = {};
  58110. serializationObject.type = this.getClassName();
  58111. serializationObject.radius = this.radius;
  58112. serializationObject.radiusRange = this.radiusRange;
  58113. serializationObject.directionRandomizer = this.directionRandomizer;
  58114. return serializationObject;
  58115. };
  58116. /**
  58117. * Parse properties from a JSON object
  58118. * @param serializationObject defines the JSON object
  58119. */
  58120. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58121. this.radius = serializationObject.radius;
  58122. this.radiusRange = serializationObject.radiusRange;
  58123. this.directionRandomizer = serializationObject.directionRandomizer;
  58124. };
  58125. return SphereParticleEmitter;
  58126. }());
  58127. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58128. /**
  58129. * Particle emitter emitting particles from the inside of a sphere.
  58130. * It emits the particles randomly between two vectors.
  58131. */
  58132. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58133. __extends(SphereDirectedParticleEmitter, _super);
  58134. /**
  58135. * Creates a new instance SphereDirectedParticleEmitter
  58136. * @param radius the radius of the emission sphere (1 by default)
  58137. * @param direction1 the min limit of the emission direction (up vector by default)
  58138. * @param direction2 the max limit of the emission direction (up vector by default)
  58139. */
  58140. function SphereDirectedParticleEmitter(radius,
  58141. /**
  58142. * The min limit of the emission direction.
  58143. */
  58144. direction1,
  58145. /**
  58146. * The max limit of the emission direction.
  58147. */
  58148. direction2) {
  58149. if (radius === void 0) { radius = 1; }
  58150. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58151. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58152. var _this = _super.call(this, radius) || this;
  58153. _this.direction1 = direction1;
  58154. _this.direction2 = direction2;
  58155. return _this;
  58156. }
  58157. /**
  58158. * Called by the particle System when the direction is computed for the created particle.
  58159. * @param worldMatrix is the world matrix of the particle system
  58160. * @param directionToUpdate is the direction vector to update with the result
  58161. * @param particle is the particle we are computed the direction for
  58162. */
  58163. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58164. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58165. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58166. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58167. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58168. };
  58169. /**
  58170. * Clones the current emitter and returns a copy of it
  58171. * @returns the new emitter
  58172. */
  58173. SphereDirectedParticleEmitter.prototype.clone = function () {
  58174. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58175. BABYLON.Tools.DeepCopy(this, newOne);
  58176. return newOne;
  58177. };
  58178. /**
  58179. * Called by the GPUParticleSystem to setup the update shader
  58180. * @param effect defines the update shader
  58181. */
  58182. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58183. effect.setFloat("radius", this.radius);
  58184. effect.setFloat("radiusRange", this.radiusRange);
  58185. effect.setVector3("direction1", this.direction1);
  58186. effect.setVector3("direction2", this.direction2);
  58187. };
  58188. /**
  58189. * Returns a string to use to update the GPU particles update shader
  58190. * @returns a string containng the defines string
  58191. */
  58192. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58193. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58194. };
  58195. /**
  58196. * Returns the string "SphereDirectedParticleEmitter"
  58197. * @returns a string containing the class name
  58198. */
  58199. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58200. return "SphereDirectedParticleEmitter";
  58201. };
  58202. /**
  58203. * Serializes the particle system to a JSON object.
  58204. * @returns the JSON object
  58205. */
  58206. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58207. var serializationObject = _super.prototype.serialize.call(this);
  58208. serializationObject.direction1 = this.direction1.asArray();
  58209. serializationObject.direction2 = this.direction2.asArray();
  58210. return serializationObject;
  58211. };
  58212. /**
  58213. * Parse properties from a JSON object
  58214. * @param serializationObject defines the JSON object
  58215. */
  58216. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58217. _super.prototype.parse.call(this, serializationObject);
  58218. this.direction1.copyFrom(serializationObject.direction1);
  58219. this.direction2.copyFrom(serializationObject.direction2);
  58220. };
  58221. return SphereDirectedParticleEmitter;
  58222. }(SphereParticleEmitter));
  58223. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58224. })(BABYLON || (BABYLON = {}));
  58225. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58226. var BABYLON;
  58227. (function (BABYLON) {
  58228. /**
  58229. * Particle emitter emitting particles from the inside of a hemisphere.
  58230. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58231. */
  58232. var HemisphericParticleEmitter = /** @class */ (function () {
  58233. /**
  58234. * Creates a new instance HemisphericParticleEmitter
  58235. * @param radius the radius of the emission hemisphere (1 by default)
  58236. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58237. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58238. */
  58239. function HemisphericParticleEmitter(
  58240. /**
  58241. * The radius of the emission hemisphere.
  58242. */
  58243. radius,
  58244. /**
  58245. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58246. */
  58247. radiusRange,
  58248. /**
  58249. * How much to randomize the particle direction [0-1].
  58250. */
  58251. directionRandomizer) {
  58252. if (radius === void 0) { radius = 1; }
  58253. if (radiusRange === void 0) { radiusRange = 1; }
  58254. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58255. this.radius = radius;
  58256. this.radiusRange = radiusRange;
  58257. this.directionRandomizer = directionRandomizer;
  58258. }
  58259. /**
  58260. * Called by the particle System when the direction is computed for the created particle.
  58261. * @param worldMatrix is the world matrix of the particle system
  58262. * @param directionToUpdate is the direction vector to update with the result
  58263. * @param particle is the particle we are computed the direction for
  58264. */
  58265. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58266. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58267. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58268. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58269. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58270. direction.x += randX;
  58271. direction.y += randY;
  58272. direction.z += randZ;
  58273. direction.normalize();
  58274. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58275. };
  58276. /**
  58277. * Called by the particle System when the position is computed for the created particle.
  58278. * @param worldMatrix is the world matrix of the particle system
  58279. * @param positionToUpdate is the position vector to update with the result
  58280. * @param particle is the particle we are computed the position for
  58281. */
  58282. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58283. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58284. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58285. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58286. var theta = Math.acos(2 * v - 1);
  58287. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58288. var randY = randRadius * Math.cos(theta);
  58289. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58291. };
  58292. /**
  58293. * Clones the current emitter and returns a copy of it
  58294. * @returns the new emitter
  58295. */
  58296. HemisphericParticleEmitter.prototype.clone = function () {
  58297. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58298. BABYLON.Tools.DeepCopy(this, newOne);
  58299. return newOne;
  58300. };
  58301. /**
  58302. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58303. * @param effect defines the update shader
  58304. */
  58305. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58306. effect.setFloat("radius", this.radius);
  58307. effect.setFloat("radiusRange", this.radiusRange);
  58308. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58309. };
  58310. /**
  58311. * Returns a string to use to update the GPU particles update shader
  58312. * @returns a string containng the defines string
  58313. */
  58314. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58315. return "#define HEMISPHERICEMITTER";
  58316. };
  58317. /**
  58318. * Returns the string "HemisphericParticleEmitter"
  58319. * @returns a string containing the class name
  58320. */
  58321. HemisphericParticleEmitter.prototype.getClassName = function () {
  58322. return "HemisphericParticleEmitter";
  58323. };
  58324. /**
  58325. * Serializes the particle system to a JSON object.
  58326. * @returns the JSON object
  58327. */
  58328. HemisphericParticleEmitter.prototype.serialize = function () {
  58329. var serializationObject = {};
  58330. serializationObject.type = this.getClassName();
  58331. serializationObject.radius = this.radius;
  58332. serializationObject.radiusRange = this.radiusRange;
  58333. serializationObject.directionRandomizer = this.directionRandomizer;
  58334. return serializationObject;
  58335. };
  58336. /**
  58337. * Parse properties from a JSON object
  58338. * @param serializationObject defines the JSON object
  58339. */
  58340. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58341. this.radius = serializationObject.radius;
  58342. this.radiusRange = serializationObject.radiusRange;
  58343. this.directionRandomizer = serializationObject.directionRandomizer;
  58344. };
  58345. return HemisphericParticleEmitter;
  58346. }());
  58347. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58348. })(BABYLON || (BABYLON = {}));
  58349. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58350. var BABYLON;
  58351. (function (BABYLON) {
  58352. /**
  58353. * Particle emitter emitting particles from a point.
  58354. * It emits the particles randomly between 2 given directions.
  58355. */
  58356. var PointParticleEmitter = /** @class */ (function () {
  58357. /**
  58358. * Creates a new instance PointParticleEmitter
  58359. */
  58360. function PointParticleEmitter() {
  58361. /**
  58362. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58363. */
  58364. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58365. /**
  58366. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58367. */
  58368. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58369. }
  58370. /**
  58371. * Called by the particle System when the direction is computed for the created particle.
  58372. * @param worldMatrix is the world matrix of the particle system
  58373. * @param directionToUpdate is the direction vector to update with the result
  58374. * @param particle is the particle we are computed the direction for
  58375. */
  58376. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58377. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58378. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58379. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58380. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58381. };
  58382. /**
  58383. * Called by the particle System when the position is computed for the created particle.
  58384. * @param worldMatrix is the world matrix of the particle system
  58385. * @param positionToUpdate is the position vector to update with the result
  58386. * @param particle is the particle we are computed the position for
  58387. */
  58388. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58389. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58390. };
  58391. /**
  58392. * Clones the current emitter and returns a copy of it
  58393. * @returns the new emitter
  58394. */
  58395. PointParticleEmitter.prototype.clone = function () {
  58396. var newOne = new PointParticleEmitter();
  58397. BABYLON.Tools.DeepCopy(this, newOne);
  58398. return newOne;
  58399. };
  58400. /**
  58401. * Called by the GPUParticleSystem to setup the update shader
  58402. * @param effect defines the update shader
  58403. */
  58404. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58405. effect.setVector3("direction1", this.direction1);
  58406. effect.setVector3("direction2", this.direction2);
  58407. };
  58408. /**
  58409. * Returns a string to use to update the GPU particles update shader
  58410. * @returns a string containng the defines string
  58411. */
  58412. PointParticleEmitter.prototype.getEffectDefines = function () {
  58413. return "#define POINTEMITTER";
  58414. };
  58415. /**
  58416. * Returns the string "PointParticleEmitter"
  58417. * @returns a string containing the class name
  58418. */
  58419. PointParticleEmitter.prototype.getClassName = function () {
  58420. return "PointParticleEmitter";
  58421. };
  58422. /**
  58423. * Serializes the particle system to a JSON object.
  58424. * @returns the JSON object
  58425. */
  58426. PointParticleEmitter.prototype.serialize = function () {
  58427. var serializationObject = {};
  58428. serializationObject.type = this.getClassName();
  58429. serializationObject.direction1 = this.direction1.asArray();
  58430. serializationObject.direction2 = this.direction2.asArray();
  58431. return serializationObject;
  58432. };
  58433. /**
  58434. * Parse properties from a JSON object
  58435. * @param serializationObject defines the JSON object
  58436. */
  58437. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58438. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58439. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58440. };
  58441. return PointParticleEmitter;
  58442. }());
  58443. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58444. })(BABYLON || (BABYLON = {}));
  58445. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58446. var BABYLON;
  58447. (function (BABYLON) {
  58448. // Adds the parsers to the scene parsers.
  58449. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58450. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58451. if (!individualParser) {
  58452. return;
  58453. }
  58454. // Particles Systems
  58455. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58456. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58457. var parsedParticleSystem = parsedData.particleSystems[index];
  58458. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58459. }
  58460. }
  58461. });
  58462. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58463. if (parsedParticleSystem.activeParticleCount) {
  58464. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58465. return ps;
  58466. }
  58467. else {
  58468. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58469. return ps;
  58470. }
  58471. });
  58472. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58473. if (uniformsNames === void 0) { uniformsNames = []; }
  58474. if (samplers === void 0) { samplers = []; }
  58475. if (defines === void 0) { defines = ""; }
  58476. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58477. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58478. if (defines.indexOf(" BILLBOARD") === -1) {
  58479. defines += "\n#define BILLBOARD\n";
  58480. }
  58481. if (samplers.indexOf("diffuseSampler") === -1) {
  58482. samplers.push("diffuseSampler");
  58483. }
  58484. return this.createEffect({
  58485. vertex: "particles",
  58486. fragmentElement: fragmentName
  58487. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58488. };
  58489. })(BABYLON || (BABYLON = {}));
  58490. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58491. var BABYLON;
  58492. (function (BABYLON) {
  58493. var ShaderMaterial = /** @class */ (function (_super) {
  58494. __extends(ShaderMaterial, _super);
  58495. function ShaderMaterial(name, scene, shaderPath, options) {
  58496. var _this = _super.call(this, name, scene) || this;
  58497. _this._textures = {};
  58498. _this._textureArrays = {};
  58499. _this._floats = {};
  58500. _this._ints = {};
  58501. _this._floatsArrays = {};
  58502. _this._colors3 = {};
  58503. _this._colors3Arrays = {};
  58504. _this._colors4 = {};
  58505. _this._vectors2 = {};
  58506. _this._vectors3 = {};
  58507. _this._vectors4 = {};
  58508. _this._matrices = {};
  58509. _this._matrices3x3 = {};
  58510. _this._matrices2x2 = {};
  58511. _this._vectors2Arrays = {};
  58512. _this._vectors3Arrays = {};
  58513. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58514. _this._shaderPath = shaderPath;
  58515. options.needAlphaBlending = options.needAlphaBlending || false;
  58516. options.needAlphaTesting = options.needAlphaTesting || false;
  58517. options.attributes = options.attributes || ["position", "normal", "uv"];
  58518. options.uniforms = options.uniforms || ["worldViewProjection"];
  58519. options.uniformBuffers = options.uniformBuffers || [];
  58520. options.samplers = options.samplers || [];
  58521. options.defines = options.defines || [];
  58522. _this._options = options;
  58523. return _this;
  58524. }
  58525. ShaderMaterial.prototype.getClassName = function () {
  58526. return "ShaderMaterial";
  58527. };
  58528. ShaderMaterial.prototype.needAlphaBlending = function () {
  58529. return this._options.needAlphaBlending;
  58530. };
  58531. ShaderMaterial.prototype.needAlphaTesting = function () {
  58532. return this._options.needAlphaTesting;
  58533. };
  58534. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58535. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58536. this._options.uniforms.push(uniformName);
  58537. }
  58538. };
  58539. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58540. if (this._options.samplers.indexOf(name) === -1) {
  58541. this._options.samplers.push(name);
  58542. }
  58543. this._textures[name] = texture;
  58544. return this;
  58545. };
  58546. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58547. if (this._options.samplers.indexOf(name) === -1) {
  58548. this._options.samplers.push(name);
  58549. }
  58550. this._checkUniform(name);
  58551. this._textureArrays[name] = textures;
  58552. return this;
  58553. };
  58554. ShaderMaterial.prototype.setFloat = function (name, value) {
  58555. this._checkUniform(name);
  58556. this._floats[name] = value;
  58557. return this;
  58558. };
  58559. ShaderMaterial.prototype.setInt = function (name, value) {
  58560. this._checkUniform(name);
  58561. this._ints[name] = value;
  58562. return this;
  58563. };
  58564. ShaderMaterial.prototype.setFloats = function (name, value) {
  58565. this._checkUniform(name);
  58566. this._floatsArrays[name] = value;
  58567. return this;
  58568. };
  58569. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58570. this._checkUniform(name);
  58571. this._colors3[name] = value;
  58572. return this;
  58573. };
  58574. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58575. this._checkUniform(name);
  58576. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58577. color.toArray(arr, arr.length);
  58578. return arr;
  58579. }, []);
  58580. return this;
  58581. };
  58582. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58583. this._checkUniform(name);
  58584. this._colors4[name] = value;
  58585. return this;
  58586. };
  58587. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58588. this._checkUniform(name);
  58589. this._vectors2[name] = value;
  58590. return this;
  58591. };
  58592. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58593. this._checkUniform(name);
  58594. this._vectors3[name] = value;
  58595. return this;
  58596. };
  58597. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58598. this._checkUniform(name);
  58599. this._vectors4[name] = value;
  58600. return this;
  58601. };
  58602. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58603. this._checkUniform(name);
  58604. this._matrices[name] = value;
  58605. return this;
  58606. };
  58607. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58608. this._checkUniform(name);
  58609. this._matrices3x3[name] = value;
  58610. return this;
  58611. };
  58612. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58613. this._checkUniform(name);
  58614. this._matrices2x2[name] = value;
  58615. return this;
  58616. };
  58617. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58618. this._checkUniform(name);
  58619. this._vectors2Arrays[name] = value;
  58620. return this;
  58621. };
  58622. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58623. this._checkUniform(name);
  58624. this._vectors3Arrays[name] = value;
  58625. return this;
  58626. };
  58627. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58628. if (!mesh) {
  58629. return true;
  58630. }
  58631. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58632. return false;
  58633. }
  58634. return false;
  58635. };
  58636. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58637. var scene = this.getScene();
  58638. var engine = scene.getEngine();
  58639. if (!this.checkReadyOnEveryCall) {
  58640. if (this._renderId === scene.getRenderId()) {
  58641. if (this._checkCache(scene, mesh, useInstances)) {
  58642. return true;
  58643. }
  58644. }
  58645. }
  58646. // Instances
  58647. var defines = [];
  58648. var attribs = [];
  58649. var fallbacks = new BABYLON.EffectFallbacks();
  58650. if (useInstances) {
  58651. defines.push("#define INSTANCES");
  58652. }
  58653. for (var index = 0; index < this._options.defines.length; index++) {
  58654. defines.push(this._options.defines[index]);
  58655. }
  58656. for (var index = 0; index < this._options.attributes.length; index++) {
  58657. attribs.push(this._options.attributes[index]);
  58658. }
  58659. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58660. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58661. defines.push("#define VERTEXCOLOR");
  58662. }
  58663. // Bones
  58664. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58665. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58666. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58667. if (mesh.numBoneInfluencers > 4) {
  58668. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58669. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58670. }
  58671. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58672. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58673. fallbacks.addCPUSkinningFallback(0, mesh);
  58674. if (this._options.uniforms.indexOf("mBones") === -1) {
  58675. this._options.uniforms.push("mBones");
  58676. }
  58677. }
  58678. else {
  58679. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58680. }
  58681. // Textures
  58682. for (var name in this._textures) {
  58683. if (!this._textures[name].isReady()) {
  58684. return false;
  58685. }
  58686. }
  58687. // Alpha test
  58688. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58689. defines.push("#define ALPHATEST");
  58690. }
  58691. var previousEffect = this._effect;
  58692. var join = defines.join("\n");
  58693. this._effect = engine.createEffect(this._shaderPath, {
  58694. attributes: attribs,
  58695. uniformsNames: this._options.uniforms,
  58696. uniformBuffersNames: this._options.uniformBuffers,
  58697. samplers: this._options.samplers,
  58698. defines: join,
  58699. fallbacks: fallbacks,
  58700. onCompiled: this.onCompiled,
  58701. onError: this.onError
  58702. }, engine);
  58703. if (!this._effect.isReady()) {
  58704. return false;
  58705. }
  58706. if (previousEffect !== this._effect) {
  58707. scene.resetCachedMaterial();
  58708. }
  58709. this._renderId = scene.getRenderId();
  58710. return true;
  58711. };
  58712. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58713. var scene = this.getScene();
  58714. if (!this._effect) {
  58715. return;
  58716. }
  58717. if (this._options.uniforms.indexOf("world") !== -1) {
  58718. this._effect.setMatrix("world", world);
  58719. }
  58720. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58721. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58722. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58723. }
  58724. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58725. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58726. }
  58727. };
  58728. ShaderMaterial.prototype.bind = function (world, mesh) {
  58729. // Std values
  58730. this.bindOnlyWorldMatrix(world);
  58731. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58732. if (this._options.uniforms.indexOf("view") !== -1) {
  58733. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58734. }
  58735. if (this._options.uniforms.indexOf("projection") !== -1) {
  58736. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58737. }
  58738. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58739. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58740. }
  58741. // Bones
  58742. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58743. var name;
  58744. // Texture
  58745. for (name in this._textures) {
  58746. this._effect.setTexture(name, this._textures[name]);
  58747. }
  58748. // Texture arrays
  58749. for (name in this._textureArrays) {
  58750. this._effect.setTextureArray(name, this._textureArrays[name]);
  58751. }
  58752. // Int
  58753. for (name in this._ints) {
  58754. this._effect.setInt(name, this._ints[name]);
  58755. }
  58756. // Float
  58757. for (name in this._floats) {
  58758. this._effect.setFloat(name, this._floats[name]);
  58759. }
  58760. // Floats
  58761. for (name in this._floatsArrays) {
  58762. this._effect.setArray(name, this._floatsArrays[name]);
  58763. }
  58764. // Color3
  58765. for (name in this._colors3) {
  58766. this._effect.setColor3(name, this._colors3[name]);
  58767. }
  58768. for (name in this._colors3Arrays) {
  58769. this._effect.setArray3(name, this._colors3Arrays[name]);
  58770. }
  58771. // Color4
  58772. for (name in this._colors4) {
  58773. var color = this._colors4[name];
  58774. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58775. }
  58776. // Vector2
  58777. for (name in this._vectors2) {
  58778. this._effect.setVector2(name, this._vectors2[name]);
  58779. }
  58780. // Vector3
  58781. for (name in this._vectors3) {
  58782. this._effect.setVector3(name, this._vectors3[name]);
  58783. }
  58784. // Vector4
  58785. for (name in this._vectors4) {
  58786. this._effect.setVector4(name, this._vectors4[name]);
  58787. }
  58788. // Matrix
  58789. for (name in this._matrices) {
  58790. this._effect.setMatrix(name, this._matrices[name]);
  58791. }
  58792. // Matrix 3x3
  58793. for (name in this._matrices3x3) {
  58794. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58795. }
  58796. // Matrix 2x2
  58797. for (name in this._matrices2x2) {
  58798. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58799. }
  58800. // Vector2Array
  58801. for (name in this._vectors2Arrays) {
  58802. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58803. }
  58804. // Vector3Array
  58805. for (name in this._vectors3Arrays) {
  58806. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58807. }
  58808. }
  58809. this._afterBind(mesh);
  58810. };
  58811. ShaderMaterial.prototype.getActiveTextures = function () {
  58812. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58813. for (var name in this._textures) {
  58814. activeTextures.push(this._textures[name]);
  58815. }
  58816. for (var name in this._textureArrays) {
  58817. var array = this._textureArrays[name];
  58818. for (var index = 0; index < array.length; index++) {
  58819. activeTextures.push(array[index]);
  58820. }
  58821. }
  58822. return activeTextures;
  58823. };
  58824. ShaderMaterial.prototype.hasTexture = function (texture) {
  58825. if (_super.prototype.hasTexture.call(this, texture)) {
  58826. return true;
  58827. }
  58828. for (var name in this._textures) {
  58829. if (this._textures[name] === texture) {
  58830. return true;
  58831. }
  58832. }
  58833. for (var name in this._textureArrays) {
  58834. var array = this._textureArrays[name];
  58835. for (var index = 0; index < array.length; index++) {
  58836. if (array[index] === texture) {
  58837. return true;
  58838. }
  58839. }
  58840. }
  58841. return false;
  58842. };
  58843. ShaderMaterial.prototype.clone = function (name) {
  58844. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58845. return newShaderMaterial;
  58846. };
  58847. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58848. if (forceDisposeTextures) {
  58849. var name;
  58850. for (name in this._textures) {
  58851. this._textures[name].dispose();
  58852. }
  58853. for (name in this._textureArrays) {
  58854. var array = this._textureArrays[name];
  58855. for (var index = 0; index < array.length; index++) {
  58856. array[index].dispose();
  58857. }
  58858. }
  58859. }
  58860. this._textures = {};
  58861. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58862. };
  58863. ShaderMaterial.prototype.serialize = function () {
  58864. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58865. serializationObject.customType = "BABYLON.ShaderMaterial";
  58866. serializationObject.options = this._options;
  58867. serializationObject.shaderPath = this._shaderPath;
  58868. var name;
  58869. // Texture
  58870. serializationObject.textures = {};
  58871. for (name in this._textures) {
  58872. serializationObject.textures[name] = this._textures[name].serialize();
  58873. }
  58874. // Texture arrays
  58875. serializationObject.textureArrays = {};
  58876. for (name in this._textureArrays) {
  58877. serializationObject.textureArrays[name] = [];
  58878. var array = this._textureArrays[name];
  58879. for (var index = 0; index < array.length; index++) {
  58880. serializationObject.textureArrays[name].push(array[index].serialize());
  58881. }
  58882. }
  58883. // Float
  58884. serializationObject.floats = {};
  58885. for (name in this._floats) {
  58886. serializationObject.floats[name] = this._floats[name];
  58887. }
  58888. // Float s
  58889. serializationObject.FloatArrays = {};
  58890. for (name in this._floatsArrays) {
  58891. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58892. }
  58893. // Color3
  58894. serializationObject.colors3 = {};
  58895. for (name in this._colors3) {
  58896. serializationObject.colors3[name] = this._colors3[name].asArray();
  58897. }
  58898. // Color3 array
  58899. serializationObject.colors3Arrays = {};
  58900. for (name in this._colors3Arrays) {
  58901. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58902. }
  58903. // Color4
  58904. serializationObject.colors4 = {};
  58905. for (name in this._colors4) {
  58906. serializationObject.colors4[name] = this._colors4[name].asArray();
  58907. }
  58908. // Vector2
  58909. serializationObject.vectors2 = {};
  58910. for (name in this._vectors2) {
  58911. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58912. }
  58913. // Vector3
  58914. serializationObject.vectors3 = {};
  58915. for (name in this._vectors3) {
  58916. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58917. }
  58918. // Vector4
  58919. serializationObject.vectors4 = {};
  58920. for (name in this._vectors4) {
  58921. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58922. }
  58923. // Matrix
  58924. serializationObject.matrices = {};
  58925. for (name in this._matrices) {
  58926. serializationObject.matrices[name] = this._matrices[name].asArray();
  58927. }
  58928. // Matrix 3x3
  58929. serializationObject.matrices3x3 = {};
  58930. for (name in this._matrices3x3) {
  58931. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58932. }
  58933. // Matrix 2x2
  58934. serializationObject.matrices2x2 = {};
  58935. for (name in this._matrices2x2) {
  58936. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58937. }
  58938. // Vector2Array
  58939. serializationObject.vectors2Arrays = {};
  58940. for (name in this._vectors2Arrays) {
  58941. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58942. }
  58943. // Vector3Array
  58944. serializationObject.vectors3Arrays = {};
  58945. for (name in this._vectors3Arrays) {
  58946. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58947. }
  58948. return serializationObject;
  58949. };
  58950. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58951. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58952. var name;
  58953. // Texture
  58954. for (name in source.textures) {
  58955. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58956. }
  58957. // Texture arrays
  58958. for (name in source.textureArrays) {
  58959. var array = source.textureArrays[name];
  58960. var textureArray = new Array();
  58961. for (var index = 0; index < array.length; index++) {
  58962. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58963. }
  58964. material.setTextureArray(name, textureArray);
  58965. }
  58966. // Float
  58967. for (name in source.floats) {
  58968. material.setFloat(name, source.floats[name]);
  58969. }
  58970. // Float s
  58971. for (name in source.floatsArrays) {
  58972. material.setFloats(name, source.floatsArrays[name]);
  58973. }
  58974. // Color3
  58975. for (name in source.colors3) {
  58976. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58977. }
  58978. // Color3 arrays
  58979. for (name in source.colors3Arrays) {
  58980. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58981. if (i % 3 === 0) {
  58982. arr.push([num]);
  58983. }
  58984. else {
  58985. arr[arr.length - 1].push(num);
  58986. }
  58987. return arr;
  58988. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58989. material.setColor3Array(name, colors);
  58990. }
  58991. // Color4
  58992. for (name in source.colors4) {
  58993. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58994. }
  58995. // Vector2
  58996. for (name in source.vectors2) {
  58997. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58998. }
  58999. // Vector3
  59000. for (name in source.vectors3) {
  59001. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59002. }
  59003. // Vector4
  59004. for (name in source.vectors4) {
  59005. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59006. }
  59007. // Matrix
  59008. for (name in source.matrices) {
  59009. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59010. }
  59011. // Matrix 3x3
  59012. for (name in source.matrices3x3) {
  59013. material.setMatrix3x3(name, source.matrices3x3[name]);
  59014. }
  59015. // Matrix 2x2
  59016. for (name in source.matrices2x2) {
  59017. material.setMatrix2x2(name, source.matrices2x2[name]);
  59018. }
  59019. // Vector2Array
  59020. for (name in source.vectors2Arrays) {
  59021. material.setArray2(name, source.vectors2Arrays[name]);
  59022. }
  59023. // Vector3Array
  59024. for (name in source.vectors3Arrays) {
  59025. material.setArray3(name, source.vectors3Arrays[name]);
  59026. }
  59027. return material;
  59028. };
  59029. return ShaderMaterial;
  59030. }(BABYLON.Material));
  59031. BABYLON.ShaderMaterial = ShaderMaterial;
  59032. })(BABYLON || (BABYLON = {}));
  59033. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59034. var BABYLON;
  59035. (function (BABYLON) {
  59036. var GroundMesh = /** @class */ (function (_super) {
  59037. __extends(GroundMesh, _super);
  59038. function GroundMesh(name, scene) {
  59039. var _this = _super.call(this, name, scene) || this;
  59040. _this.generateOctree = false;
  59041. return _this;
  59042. }
  59043. GroundMesh.prototype.getClassName = function () {
  59044. return "GroundMesh";
  59045. };
  59046. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59047. get: function () {
  59048. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59049. },
  59050. enumerable: true,
  59051. configurable: true
  59052. });
  59053. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59054. get: function () {
  59055. return this._subdivisionsX;
  59056. },
  59057. enumerable: true,
  59058. configurable: true
  59059. });
  59060. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59061. get: function () {
  59062. return this._subdivisionsY;
  59063. },
  59064. enumerable: true,
  59065. configurable: true
  59066. });
  59067. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59068. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59069. this._subdivisionsX = chunksCount;
  59070. this._subdivisionsY = chunksCount;
  59071. this.subdivide(chunksCount);
  59072. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59073. };
  59074. /**
  59075. * Returns a height (y) value in the Worl system :
  59076. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59077. * Returns the ground y position if (x, z) are outside the ground surface.
  59078. */
  59079. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59080. var world = this.getWorldMatrix();
  59081. var invMat = BABYLON.Tmp.Matrix[5];
  59082. world.invertToRef(invMat);
  59083. var tmpVect = BABYLON.Tmp.Vector3[8];
  59084. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59085. x = tmpVect.x;
  59086. z = tmpVect.z;
  59087. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59088. return this.position.y;
  59089. }
  59090. if (!this._heightQuads || this._heightQuads.length == 0) {
  59091. this._initHeightQuads();
  59092. this._computeHeightQuads();
  59093. }
  59094. var facet = this._getFacetAt(x, z);
  59095. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59096. // return y in the World system
  59097. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59098. return tmpVect.y;
  59099. };
  59100. /**
  59101. * Returns a normalized vector (Vector3) orthogonal to the ground
  59102. * at the ground coordinates (x, z) expressed in the World system.
  59103. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59104. */
  59105. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59106. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59107. this.getNormalAtCoordinatesToRef(x, z, normal);
  59108. return normal;
  59109. };
  59110. /**
  59111. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59112. * at the ground coordinates (x, z) expressed in the World system.
  59113. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59114. * Returns the GroundMesh.
  59115. */
  59116. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59117. var world = this.getWorldMatrix();
  59118. var tmpMat = BABYLON.Tmp.Matrix[5];
  59119. world.invertToRef(tmpMat);
  59120. var tmpVect = BABYLON.Tmp.Vector3[8];
  59121. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59122. x = tmpVect.x;
  59123. z = tmpVect.z;
  59124. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59125. return this;
  59126. }
  59127. if (!this._heightQuads || this._heightQuads.length == 0) {
  59128. this._initHeightQuads();
  59129. this._computeHeightQuads();
  59130. }
  59131. var facet = this._getFacetAt(x, z);
  59132. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59133. return this;
  59134. };
  59135. /**
  59136. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59137. * if the ground has been updated.
  59138. * This can be used in the render loop.
  59139. * Returns the GroundMesh.
  59140. */
  59141. GroundMesh.prototype.updateCoordinateHeights = function () {
  59142. if (!this._heightQuads || this._heightQuads.length == 0) {
  59143. this._initHeightQuads();
  59144. }
  59145. this._computeHeightQuads();
  59146. return this;
  59147. };
  59148. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59149. GroundMesh.prototype._getFacetAt = function (x, z) {
  59150. // retrieve col and row from x, z coordinates in the ground local system
  59151. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59152. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59153. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59154. var facet;
  59155. if (z < quad.slope.x * x + quad.slope.y) {
  59156. facet = quad.facet1;
  59157. }
  59158. else {
  59159. facet = quad.facet2;
  59160. }
  59161. return facet;
  59162. };
  59163. // Creates and populates the heightMap array with "facet" elements :
  59164. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59165. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59166. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59167. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59168. // Returns the GroundMesh.
  59169. GroundMesh.prototype._initHeightQuads = function () {
  59170. var subdivisionsX = this._subdivisionsX;
  59171. var subdivisionsY = this._subdivisionsY;
  59172. this._heightQuads = new Array();
  59173. for (var row = 0; row < subdivisionsY; row++) {
  59174. for (var col = 0; col < subdivisionsX; col++) {
  59175. 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) };
  59176. this._heightQuads[row * subdivisionsX + col] = quad;
  59177. }
  59178. }
  59179. return this;
  59180. };
  59181. // Compute each quad element values and update the the heightMap array :
  59182. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59183. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59184. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59185. // Returns the GroundMesh.
  59186. GroundMesh.prototype._computeHeightQuads = function () {
  59187. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59188. if (!positions) {
  59189. return this;
  59190. }
  59191. var v1 = BABYLON.Tmp.Vector3[3];
  59192. var v2 = BABYLON.Tmp.Vector3[2];
  59193. var v3 = BABYLON.Tmp.Vector3[1];
  59194. var v4 = BABYLON.Tmp.Vector3[0];
  59195. var v1v2 = BABYLON.Tmp.Vector3[4];
  59196. var v1v3 = BABYLON.Tmp.Vector3[5];
  59197. var v1v4 = BABYLON.Tmp.Vector3[6];
  59198. var norm1 = BABYLON.Tmp.Vector3[7];
  59199. var norm2 = BABYLON.Tmp.Vector3[8];
  59200. var i = 0;
  59201. var j = 0;
  59202. var k = 0;
  59203. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59204. var h = 0;
  59205. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59206. var d2 = 0;
  59207. var subdivisionsX = this._subdivisionsX;
  59208. var subdivisionsY = this._subdivisionsY;
  59209. for (var row = 0; row < subdivisionsY; row++) {
  59210. for (var col = 0; col < subdivisionsX; col++) {
  59211. i = col * 3;
  59212. j = row * (subdivisionsX + 1) * 3;
  59213. k = (row + 1) * (subdivisionsX + 1) * 3;
  59214. v1.x = positions[j + i];
  59215. v1.y = positions[j + i + 1];
  59216. v1.z = positions[j + i + 2];
  59217. v2.x = positions[j + i + 3];
  59218. v2.y = positions[j + i + 4];
  59219. v2.z = positions[j + i + 5];
  59220. v3.x = positions[k + i];
  59221. v3.y = positions[k + i + 1];
  59222. v3.z = positions[k + i + 2];
  59223. v4.x = positions[k + i + 3];
  59224. v4.y = positions[k + i + 4];
  59225. v4.z = positions[k + i + 5];
  59226. // 2D slope V1V4
  59227. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59228. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59229. // facet equations :
  59230. // we compute each facet normal vector
  59231. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59232. // we compute the value d by applying the equation to v1 which belongs to the plane
  59233. // then we store the facet equation in a Vector4
  59234. v2.subtractToRef(v1, v1v2);
  59235. v3.subtractToRef(v1, v1v3);
  59236. v4.subtractToRef(v1, v1v4);
  59237. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59238. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59239. norm1.normalize();
  59240. norm2.normalize();
  59241. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59242. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59243. var quad = this._heightQuads[row * subdivisionsX + col];
  59244. quad.slope.copyFromFloats(cd, h);
  59245. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59246. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59247. }
  59248. }
  59249. return this;
  59250. };
  59251. GroundMesh.prototype.serialize = function (serializationObject) {
  59252. _super.prototype.serialize.call(this, serializationObject);
  59253. serializationObject.subdivisionsX = this._subdivisionsX;
  59254. serializationObject.subdivisionsY = this._subdivisionsY;
  59255. serializationObject.minX = this._minX;
  59256. serializationObject.maxX = this._maxX;
  59257. serializationObject.minZ = this._minZ;
  59258. serializationObject.maxZ = this._maxZ;
  59259. serializationObject.width = this._width;
  59260. serializationObject.height = this._height;
  59261. };
  59262. GroundMesh.Parse = function (parsedMesh, scene) {
  59263. var result = new GroundMesh(parsedMesh.name, scene);
  59264. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59265. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59266. result._minX = parsedMesh.minX;
  59267. result._maxX = parsedMesh.maxX;
  59268. result._minZ = parsedMesh.minZ;
  59269. result._maxZ = parsedMesh.maxZ;
  59270. result._width = parsedMesh.width;
  59271. result._height = parsedMesh.height;
  59272. return result;
  59273. };
  59274. return GroundMesh;
  59275. }(BABYLON.Mesh));
  59276. BABYLON.GroundMesh = GroundMesh;
  59277. })(BABYLON || (BABYLON = {}));
  59278. //# sourceMappingURL=babylon.groundMesh.js.map
  59279. var BABYLON;
  59280. (function (BABYLON) {
  59281. /**
  59282. * Creates an instance based on a source mesh.
  59283. */
  59284. var InstancedMesh = /** @class */ (function (_super) {
  59285. __extends(InstancedMesh, _super);
  59286. function InstancedMesh(name, source) {
  59287. var _this = _super.call(this, name, source.getScene()) || this;
  59288. source.instances.push(_this);
  59289. _this._sourceMesh = source;
  59290. _this.position.copyFrom(source.position);
  59291. _this.rotation.copyFrom(source.rotation);
  59292. _this.scaling.copyFrom(source.scaling);
  59293. if (source.rotationQuaternion) {
  59294. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59295. }
  59296. _this.infiniteDistance = source.infiniteDistance;
  59297. _this.setPivotMatrix(source.getPivotMatrix());
  59298. _this.refreshBoundingInfo();
  59299. _this._syncSubMeshes();
  59300. return _this;
  59301. }
  59302. /**
  59303. * Returns the string "InstancedMesh".
  59304. */
  59305. InstancedMesh.prototype.getClassName = function () {
  59306. return "InstancedMesh";
  59307. };
  59308. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59309. // Methods
  59310. get: function () {
  59311. return this._sourceMesh.receiveShadows;
  59312. },
  59313. enumerable: true,
  59314. configurable: true
  59315. });
  59316. Object.defineProperty(InstancedMesh.prototype, "material", {
  59317. get: function () {
  59318. return this._sourceMesh.material;
  59319. },
  59320. enumerable: true,
  59321. configurable: true
  59322. });
  59323. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59324. get: function () {
  59325. return this._sourceMesh.visibility;
  59326. },
  59327. enumerable: true,
  59328. configurable: true
  59329. });
  59330. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59331. get: function () {
  59332. return this._sourceMesh.skeleton;
  59333. },
  59334. enumerable: true,
  59335. configurable: true
  59336. });
  59337. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59338. get: function () {
  59339. return this._sourceMesh.renderingGroupId;
  59340. },
  59341. set: function (value) {
  59342. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59343. return;
  59344. }
  59345. //no-op with warning
  59346. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59347. },
  59348. enumerable: true,
  59349. configurable: true
  59350. });
  59351. /**
  59352. * Returns the total number of vertices (integer).
  59353. */
  59354. InstancedMesh.prototype.getTotalVertices = function () {
  59355. return this._sourceMesh.getTotalVertices();
  59356. };
  59357. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59358. get: function () {
  59359. return this._sourceMesh;
  59360. },
  59361. enumerable: true,
  59362. configurable: true
  59363. });
  59364. /**
  59365. * Is this node ready to be used/rendered
  59366. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59367. * @return {boolean} is it ready
  59368. */
  59369. InstancedMesh.prototype.isReady = function (completeCheck) {
  59370. if (completeCheck === void 0) { completeCheck = false; }
  59371. return this._sourceMesh.isReady(completeCheck, true);
  59372. };
  59373. /**
  59374. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59375. */
  59376. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59377. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59378. };
  59379. /**
  59380. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59381. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59382. * The `data` are either a numeric array either a Float32Array.
  59383. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59384. * 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).
  59385. * Note that a new underlying VertexBuffer object is created each call.
  59386. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59387. *
  59388. * Possible `kind` values :
  59389. * - BABYLON.VertexBuffer.PositionKind
  59390. * - BABYLON.VertexBuffer.UVKind
  59391. * - BABYLON.VertexBuffer.UV2Kind
  59392. * - BABYLON.VertexBuffer.UV3Kind
  59393. * - BABYLON.VertexBuffer.UV4Kind
  59394. * - BABYLON.VertexBuffer.UV5Kind
  59395. * - BABYLON.VertexBuffer.UV6Kind
  59396. * - BABYLON.VertexBuffer.ColorKind
  59397. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59398. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59399. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59400. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59401. *
  59402. * Returns the Mesh.
  59403. */
  59404. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59405. if (this.sourceMesh) {
  59406. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59407. }
  59408. return this.sourceMesh;
  59409. };
  59410. /**
  59411. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59412. * If the mesh has no geometry, it is simply returned as it is.
  59413. * The `data` are either a numeric array either a Float32Array.
  59414. * No new underlying VertexBuffer object is created.
  59415. * 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.
  59416. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59417. *
  59418. * Possible `kind` values :
  59419. * - BABYLON.VertexBuffer.PositionKind
  59420. * - BABYLON.VertexBuffer.UVKind
  59421. * - BABYLON.VertexBuffer.UV2Kind
  59422. * - BABYLON.VertexBuffer.UV3Kind
  59423. * - BABYLON.VertexBuffer.UV4Kind
  59424. * - BABYLON.VertexBuffer.UV5Kind
  59425. * - BABYLON.VertexBuffer.UV6Kind
  59426. * - BABYLON.VertexBuffer.ColorKind
  59427. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59428. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59429. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59430. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59431. *
  59432. * Returns the Mesh.
  59433. */
  59434. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59435. if (this.sourceMesh) {
  59436. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59437. }
  59438. return this.sourceMesh;
  59439. };
  59440. /**
  59441. * Sets the mesh indices.
  59442. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59443. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59444. * This method creates a new index buffer each call.
  59445. * Returns the Mesh.
  59446. */
  59447. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59448. if (totalVertices === void 0) { totalVertices = null; }
  59449. if (this.sourceMesh) {
  59450. this.sourceMesh.setIndices(indices, totalVertices);
  59451. }
  59452. return this.sourceMesh;
  59453. };
  59454. /**
  59455. * Boolean : True if the mesh owns the requested kind of data.
  59456. */
  59457. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59458. return this._sourceMesh.isVerticesDataPresent(kind);
  59459. };
  59460. /**
  59461. * Returns an array of indices (IndicesArray).
  59462. */
  59463. InstancedMesh.prototype.getIndices = function () {
  59464. return this._sourceMesh.getIndices();
  59465. };
  59466. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59467. get: function () {
  59468. return this._sourceMesh._positions;
  59469. },
  59470. enumerable: true,
  59471. configurable: true
  59472. });
  59473. /**
  59474. * Sets a new updated BoundingInfo to the mesh.
  59475. * Returns the mesh.
  59476. */
  59477. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59478. var meshBB = this._sourceMesh.getBoundingInfo();
  59479. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59480. this._updateBoundingInfo();
  59481. return this;
  59482. };
  59483. /** @hidden */
  59484. InstancedMesh.prototype._preActivate = function () {
  59485. if (this._currentLOD) {
  59486. this._currentLOD._preActivate();
  59487. }
  59488. return this;
  59489. };
  59490. /** @hidden */
  59491. InstancedMesh.prototype._activate = function (renderId) {
  59492. if (this._currentLOD) {
  59493. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59494. }
  59495. return this;
  59496. };
  59497. /**
  59498. * Returns the current associated LOD AbstractMesh.
  59499. */
  59500. InstancedMesh.prototype.getLOD = function (camera) {
  59501. if (!camera) {
  59502. return this;
  59503. }
  59504. var boundingInfo = this.getBoundingInfo();
  59505. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59506. if (this._currentLOD === this.sourceMesh) {
  59507. return this;
  59508. }
  59509. return this._currentLOD;
  59510. };
  59511. /** @hidden */
  59512. InstancedMesh.prototype._syncSubMeshes = function () {
  59513. this.releaseSubMeshes();
  59514. if (this._sourceMesh.subMeshes) {
  59515. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59516. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59517. }
  59518. }
  59519. return this;
  59520. };
  59521. /** @hidden */
  59522. InstancedMesh.prototype._generatePointsArray = function () {
  59523. return this._sourceMesh._generatePointsArray();
  59524. };
  59525. /**
  59526. * Creates a new InstancedMesh from the current mesh.
  59527. * - name (string) : the cloned mesh name
  59528. * - newParent (optional Node) : the optional Node to parent the clone to.
  59529. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59530. *
  59531. * Returns the clone.
  59532. */
  59533. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59534. var result = this._sourceMesh.createInstance(name);
  59535. // Deep copy
  59536. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59537. // Bounding info
  59538. this.refreshBoundingInfo();
  59539. // Parent
  59540. if (newParent) {
  59541. result.parent = newParent;
  59542. }
  59543. if (!doNotCloneChildren) {
  59544. // Children
  59545. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59546. var mesh = this.getScene().meshes[index];
  59547. if (mesh.parent === this) {
  59548. mesh.clone(mesh.name, result);
  59549. }
  59550. }
  59551. }
  59552. result.computeWorldMatrix(true);
  59553. return result;
  59554. };
  59555. /**
  59556. * Disposes the InstancedMesh.
  59557. * Returns nothing.
  59558. */
  59559. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59560. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59561. // Remove from mesh
  59562. var index = this._sourceMesh.instances.indexOf(this);
  59563. this._sourceMesh.instances.splice(index, 1);
  59564. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59565. };
  59566. return InstancedMesh;
  59567. }(BABYLON.AbstractMesh));
  59568. BABYLON.InstancedMesh = InstancedMesh;
  59569. })(BABYLON || (BABYLON = {}));
  59570. //# sourceMappingURL=babylon.instancedMesh.js.map
  59571. var BABYLON;
  59572. (function (BABYLON) {
  59573. var LinesMesh = /** @class */ (function (_super) {
  59574. __extends(LinesMesh, _super);
  59575. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59576. if (scene === void 0) { scene = null; }
  59577. if (parent === void 0) { parent = null; }
  59578. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59579. _this.useVertexColor = useVertexColor;
  59580. _this.useVertexAlpha = useVertexAlpha;
  59581. _this.color = new BABYLON.Color3(1, 1, 1);
  59582. _this.alpha = 1;
  59583. if (source) {
  59584. _this.color = source.color.clone();
  59585. _this.alpha = source.alpha;
  59586. _this.useVertexColor = source.useVertexColor;
  59587. _this.useVertexAlpha = source.useVertexAlpha;
  59588. }
  59589. _this._intersectionThreshold = 0.1;
  59590. var defines = [];
  59591. var options = {
  59592. attributes: [BABYLON.VertexBuffer.PositionKind],
  59593. uniforms: ["world", "viewProjection"],
  59594. needAlphaBlending: true,
  59595. defines: defines
  59596. };
  59597. if (useVertexAlpha === false) {
  59598. options.needAlphaBlending = false;
  59599. }
  59600. if (!useVertexColor) {
  59601. options.uniforms.push("color");
  59602. }
  59603. else {
  59604. options.defines.push("#define VERTEXCOLOR");
  59605. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59606. }
  59607. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59608. return _this;
  59609. }
  59610. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59611. /**
  59612. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59613. * This margin is expressed in world space coordinates, so its value may vary.
  59614. * Default value is 0.1
  59615. * @returns the intersection Threshold value.
  59616. */
  59617. get: function () {
  59618. return this._intersectionThreshold;
  59619. },
  59620. /**
  59621. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59622. * This margin is expressed in world space coordinates, so its value may vary.
  59623. * @param value the new threshold to apply
  59624. */
  59625. set: function (value) {
  59626. if (this._intersectionThreshold === value) {
  59627. return;
  59628. }
  59629. this._intersectionThreshold = value;
  59630. if (this.geometry) {
  59631. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59632. }
  59633. },
  59634. enumerable: true,
  59635. configurable: true
  59636. });
  59637. /**
  59638. * Returns the string "LineMesh"
  59639. */
  59640. LinesMesh.prototype.getClassName = function () {
  59641. return "LinesMesh";
  59642. };
  59643. Object.defineProperty(LinesMesh.prototype, "material", {
  59644. /**
  59645. * @hidden
  59646. */
  59647. get: function () {
  59648. return this._colorShader;
  59649. },
  59650. /**
  59651. * @hidden
  59652. */
  59653. set: function (value) {
  59654. // Do nothing
  59655. },
  59656. enumerable: true,
  59657. configurable: true
  59658. });
  59659. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59660. /**
  59661. * @hidden
  59662. */
  59663. get: function () {
  59664. return false;
  59665. },
  59666. enumerable: true,
  59667. configurable: true
  59668. });
  59669. LinesMesh.prototype.createInstance = function (name) {
  59670. throw new Error("LinesMeshes do not support createInstance.");
  59671. };
  59672. /** @hidden */
  59673. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59674. if (!this._geometry) {
  59675. return this;
  59676. }
  59677. // VBOs
  59678. this._geometry._bind(this._colorShader.getEffect());
  59679. // Color
  59680. if (!this.useVertexColor) {
  59681. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59682. }
  59683. return this;
  59684. };
  59685. /** @hidden */
  59686. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59687. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59688. return this;
  59689. }
  59690. var engine = this.getScene().getEngine();
  59691. // Draw order
  59692. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59693. return this;
  59694. };
  59695. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59696. this._colorShader.dispose();
  59697. _super.prototype.dispose.call(this, doNotRecurse);
  59698. };
  59699. /**
  59700. * Returns a new LineMesh object cloned from the current one.
  59701. */
  59702. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59703. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59704. };
  59705. /**
  59706. * Enables the edge rendering mode on the mesh.
  59707. * This mode makes the mesh edges visible
  59708. * @param epsilon defines the maximal distance between two angles to detect a face
  59709. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  59710. * @returns the currentAbstractMesh
  59711. * @see https://www.babylonjs-playground.com/#19O9TU#0
  59712. */
  59713. LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  59714. if (epsilon === void 0) { epsilon = 0.95; }
  59715. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  59716. this.disableEdgesRendering();
  59717. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  59718. return this;
  59719. };
  59720. return LinesMesh;
  59721. }(BABYLON.Mesh));
  59722. BABYLON.LinesMesh = LinesMesh;
  59723. })(BABYLON || (BABYLON = {}));
  59724. //# sourceMappingURL=babylon.linesMesh.js.map
  59725. var BABYLON;
  59726. (function (BABYLON) {
  59727. /**
  59728. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59729. * The underlying implementation relies on an associative array to ensure the best performances.
  59730. * The value can be anything including 'null' but except 'undefined'
  59731. */
  59732. var StringDictionary = /** @class */ (function () {
  59733. function StringDictionary() {
  59734. this._count = 0;
  59735. this._data = {};
  59736. }
  59737. /**
  59738. * This will clear this dictionary and copy the content from the 'source' one.
  59739. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59740. * @param source the dictionary to take the content from and copy to this dictionary
  59741. */
  59742. StringDictionary.prototype.copyFrom = function (source) {
  59743. var _this = this;
  59744. this.clear();
  59745. source.forEach(function (t, v) { return _this.add(t, v); });
  59746. };
  59747. /**
  59748. * Get a value based from its key
  59749. * @param key the given key to get the matching value from
  59750. * @return the value if found, otherwise undefined is returned
  59751. */
  59752. StringDictionary.prototype.get = function (key) {
  59753. var val = this._data[key];
  59754. if (val !== undefined) {
  59755. return val;
  59756. }
  59757. return undefined;
  59758. };
  59759. /**
  59760. * Get a value from its key or add it if it doesn't exist.
  59761. * This method will ensure you that a given key/data will be present in the dictionary.
  59762. * @param key the given key to get the matching value from
  59763. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59764. * The factory will only be invoked if there's no data for the given key.
  59765. * @return the value corresponding to the key.
  59766. */
  59767. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59768. var val = this.get(key);
  59769. if (val !== undefined) {
  59770. return val;
  59771. }
  59772. val = factory(key);
  59773. if (val) {
  59774. this.add(key, val);
  59775. }
  59776. return val;
  59777. };
  59778. /**
  59779. * Get a value from its key if present in the dictionary otherwise add it
  59780. * @param key the key to get the value from
  59781. * @param val if there's no such key/value pair in the dictionary add it with this value
  59782. * @return the value corresponding to the key
  59783. */
  59784. StringDictionary.prototype.getOrAdd = function (key, val) {
  59785. var curVal = this.get(key);
  59786. if (curVal !== undefined) {
  59787. return curVal;
  59788. }
  59789. this.add(key, val);
  59790. return val;
  59791. };
  59792. /**
  59793. * Check if there's a given key in the dictionary
  59794. * @param key the key to check for
  59795. * @return true if the key is present, false otherwise
  59796. */
  59797. StringDictionary.prototype.contains = function (key) {
  59798. return this._data[key] !== undefined;
  59799. };
  59800. /**
  59801. * Add a new key and its corresponding value
  59802. * @param key the key to add
  59803. * @param value the value corresponding to the key
  59804. * @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
  59805. */
  59806. StringDictionary.prototype.add = function (key, value) {
  59807. if (this._data[key] !== undefined) {
  59808. return false;
  59809. }
  59810. this._data[key] = value;
  59811. ++this._count;
  59812. return true;
  59813. };
  59814. StringDictionary.prototype.set = function (key, value) {
  59815. if (this._data[key] === undefined) {
  59816. return false;
  59817. }
  59818. this._data[key] = value;
  59819. return true;
  59820. };
  59821. /**
  59822. * Get the element of the given key and remove it from the dictionary
  59823. * @param key
  59824. */
  59825. StringDictionary.prototype.getAndRemove = function (key) {
  59826. var val = this.get(key);
  59827. if (val !== undefined) {
  59828. delete this._data[key];
  59829. --this._count;
  59830. return val;
  59831. }
  59832. return null;
  59833. };
  59834. /**
  59835. * Remove a key/value from the dictionary.
  59836. * @param key the key to remove
  59837. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59838. */
  59839. StringDictionary.prototype.remove = function (key) {
  59840. if (this.contains(key)) {
  59841. delete this._data[key];
  59842. --this._count;
  59843. return true;
  59844. }
  59845. return false;
  59846. };
  59847. /**
  59848. * Clear the whole content of the dictionary
  59849. */
  59850. StringDictionary.prototype.clear = function () {
  59851. this._data = {};
  59852. this._count = 0;
  59853. };
  59854. Object.defineProperty(StringDictionary.prototype, "count", {
  59855. get: function () {
  59856. return this._count;
  59857. },
  59858. enumerable: true,
  59859. configurable: true
  59860. });
  59861. /**
  59862. * Execute a callback on each key/val of the dictionary.
  59863. * Note that you can remove any element in this dictionary in the callback implementation
  59864. * @param callback the callback to execute on a given key/value pair
  59865. */
  59866. StringDictionary.prototype.forEach = function (callback) {
  59867. for (var cur in this._data) {
  59868. var val = this._data[cur];
  59869. callback(cur, val);
  59870. }
  59871. };
  59872. /**
  59873. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59874. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59875. * Note that you can remove any element in this dictionary in the callback implementation
  59876. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59877. */
  59878. StringDictionary.prototype.first = function (callback) {
  59879. for (var cur in this._data) {
  59880. var val = this._data[cur];
  59881. var res = callback(cur, val);
  59882. if (res) {
  59883. return res;
  59884. }
  59885. }
  59886. return null;
  59887. };
  59888. return StringDictionary;
  59889. }());
  59890. BABYLON.StringDictionary = StringDictionary;
  59891. })(BABYLON || (BABYLON = {}));
  59892. //# sourceMappingURL=babylon.stringDictionary.js.map
  59893. var BABYLON;
  59894. (function (BABYLON) {
  59895. var Debug;
  59896. (function (Debug) {
  59897. /**
  59898. * Class used to render a debug view of a given skeleton
  59899. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59900. */
  59901. var SkeletonViewer = /** @class */ (function () {
  59902. /**
  59903. * Creates a new SkeletonViewer
  59904. * @param skeleton defines the skeleton to render
  59905. * @param mesh defines the mesh attached to the skeleton
  59906. * @param scene defines the hosting scene
  59907. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59908. * @param renderingGroupId defines the rendering group id to use with the viewer
  59909. */
  59910. function SkeletonViewer(
  59911. /** defines the skeleton to render */
  59912. skeleton,
  59913. /** defines the mesh attached to the skeleton */
  59914. mesh, scene,
  59915. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59916. autoUpdateBonesMatrices,
  59917. /** defines the rendering group id to use with the viewer */
  59918. renderingGroupId) {
  59919. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59920. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59921. this.skeleton = skeleton;
  59922. this.mesh = mesh;
  59923. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59924. this.renderingGroupId = renderingGroupId;
  59925. /** Gets or sets the color used to render the skeleton */
  59926. this.color = BABYLON.Color3.White();
  59927. this._debugLines = new Array();
  59928. this._isEnabled = false;
  59929. this._scene = scene;
  59930. this.update();
  59931. this._renderFunction = this.update.bind(this);
  59932. }
  59933. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59934. get: function () {
  59935. return this._isEnabled;
  59936. },
  59937. /** Gets or sets a boolean indicating if the viewer is enabled */
  59938. set: function (value) {
  59939. if (this._isEnabled === value) {
  59940. return;
  59941. }
  59942. this._isEnabled = value;
  59943. if (value) {
  59944. this._scene.registerBeforeRender(this._renderFunction);
  59945. }
  59946. else {
  59947. this._scene.unregisterBeforeRender(this._renderFunction);
  59948. }
  59949. },
  59950. enumerable: true,
  59951. configurable: true
  59952. });
  59953. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59954. if (x === void 0) { x = 0; }
  59955. if (y === void 0) { y = 0; }
  59956. if (z === void 0) { z = 0; }
  59957. var tmat = BABYLON.Tmp.Matrix[0];
  59958. var parentBone = bone.getParent();
  59959. tmat.copyFrom(bone.getLocalMatrix());
  59960. if (x !== 0 || y !== 0 || z !== 0) {
  59961. var tmat2 = BABYLON.Tmp.Matrix[1];
  59962. BABYLON.Matrix.IdentityToRef(tmat2);
  59963. tmat2.m[12] = x;
  59964. tmat2.m[13] = y;
  59965. tmat2.m[14] = z;
  59966. tmat2.multiplyToRef(tmat, tmat);
  59967. }
  59968. if (parentBone) {
  59969. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59970. }
  59971. tmat.multiplyToRef(meshMat, tmat);
  59972. position.x = tmat.m[12];
  59973. position.y = tmat.m[13];
  59974. position.z = tmat.m[14];
  59975. };
  59976. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59977. var len = bones.length;
  59978. var meshPos = this.mesh.position;
  59979. for (var i = 0; i < len; i++) {
  59980. var bone = bones[i];
  59981. var points = this._debugLines[i];
  59982. if (!points) {
  59983. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59984. this._debugLines[i] = points;
  59985. }
  59986. this._getBonePosition(points[0], bone, meshMat);
  59987. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59988. points[0].subtractInPlace(meshPos);
  59989. points[1].subtractInPlace(meshPos);
  59990. }
  59991. };
  59992. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59993. var len = bones.length;
  59994. var boneNum = 0;
  59995. var meshPos = this.mesh.position;
  59996. for (var i = len - 1; i >= 0; i--) {
  59997. var childBone = bones[i];
  59998. var parentBone = childBone.getParent();
  59999. if (!parentBone) {
  60000. continue;
  60001. }
  60002. var points = this._debugLines[boneNum];
  60003. if (!points) {
  60004. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60005. this._debugLines[boneNum] = points;
  60006. }
  60007. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60008. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60009. points[0].subtractInPlace(meshPos);
  60010. points[1].subtractInPlace(meshPos);
  60011. boneNum++;
  60012. }
  60013. };
  60014. /** Update the viewer to sync with current skeleton state */
  60015. SkeletonViewer.prototype.update = function () {
  60016. if (this.autoUpdateBonesMatrices) {
  60017. this.skeleton.computeAbsoluteTransforms();
  60018. }
  60019. if (this.skeleton.bones[0].length === undefined) {
  60020. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60021. }
  60022. else {
  60023. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60024. }
  60025. if (!this._debugMesh) {
  60026. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60027. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60028. }
  60029. else {
  60030. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60031. }
  60032. this._debugMesh.position.copyFrom(this.mesh.position);
  60033. this._debugMesh.color = this.color;
  60034. };
  60035. /** Release associated resources */
  60036. SkeletonViewer.prototype.dispose = function () {
  60037. if (this._debugMesh) {
  60038. this.isEnabled = false;
  60039. this._debugMesh.dispose();
  60040. this._debugMesh = null;
  60041. }
  60042. };
  60043. return SkeletonViewer;
  60044. }());
  60045. Debug.SkeletonViewer = SkeletonViewer;
  60046. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60047. })(BABYLON || (BABYLON = {}));
  60048. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60049. /**
  60050. * Module Debug contains the (visual) components to debug a scene correctly
  60051. */
  60052. var BABYLON;
  60053. (function (BABYLON) {
  60054. var Debug;
  60055. (function (Debug) {
  60056. /**
  60057. * The Axes viewer will show 3 axes in a specific point in space
  60058. */
  60059. var AxesViewer = /** @class */ (function () {
  60060. /**
  60061. * Creates a new AxesViewer
  60062. * @param scene defines the hosting scene
  60063. * @param scaleLines defines a number used to scale line length (1 by default)
  60064. */
  60065. function AxesViewer(scene, scaleLines) {
  60066. if (scaleLines === void 0) { scaleLines = 1; }
  60067. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60068. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60069. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60070. /**
  60071. * Gets or sets a number used to scale line length
  60072. */
  60073. this.scaleLines = 1;
  60074. this.scaleLines = scaleLines;
  60075. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60076. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60077. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60078. this._xmesh.renderingGroupId = 2;
  60079. this._ymesh.renderingGroupId = 2;
  60080. this._zmesh.renderingGroupId = 2;
  60081. this._xmesh.material.checkReadyOnlyOnce = true;
  60082. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60083. this._ymesh.material.checkReadyOnlyOnce = true;
  60084. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60085. this._zmesh.material.checkReadyOnlyOnce = true;
  60086. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60087. this.scene = scene;
  60088. }
  60089. /**
  60090. * Force the viewer to update
  60091. * @param position defines the position of the viewer
  60092. * @param xaxis defines the x axis of the viewer
  60093. * @param yaxis defines the y axis of the viewer
  60094. * @param zaxis defines the z axis of the viewer
  60095. */
  60096. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60097. var scaleLines = this.scaleLines;
  60098. if (this._xmesh) {
  60099. this._xmesh.position.copyFrom(position);
  60100. }
  60101. if (this._ymesh) {
  60102. this._ymesh.position.copyFrom(position);
  60103. }
  60104. if (this._zmesh) {
  60105. this._zmesh.position.copyFrom(position);
  60106. }
  60107. var point2 = this._xline[1];
  60108. point2.x = xaxis.x * scaleLines;
  60109. point2.y = xaxis.y * scaleLines;
  60110. point2.z = xaxis.z * scaleLines;
  60111. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60112. point2 = this._yline[1];
  60113. point2.x = yaxis.x * scaleLines;
  60114. point2.y = yaxis.y * scaleLines;
  60115. point2.z = yaxis.z * scaleLines;
  60116. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60117. point2 = this._zline[1];
  60118. point2.x = zaxis.x * scaleLines;
  60119. point2.y = zaxis.y * scaleLines;
  60120. point2.z = zaxis.z * scaleLines;
  60121. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60122. };
  60123. /** Releases resources */
  60124. AxesViewer.prototype.dispose = function () {
  60125. if (this._xmesh) {
  60126. this._xmesh.dispose();
  60127. }
  60128. if (this._ymesh) {
  60129. this._ymesh.dispose();
  60130. }
  60131. if (this._zmesh) {
  60132. this._zmesh.dispose();
  60133. }
  60134. this._xmesh = null;
  60135. this._ymesh = null;
  60136. this._zmesh = null;
  60137. this.scene = null;
  60138. };
  60139. return AxesViewer;
  60140. }());
  60141. Debug.AxesViewer = AxesViewer;
  60142. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60143. })(BABYLON || (BABYLON = {}));
  60144. //# sourceMappingURL=babylon.axesViewer.js.map
  60145. var BABYLON;
  60146. (function (BABYLON) {
  60147. var Debug;
  60148. (function (Debug) {
  60149. /**
  60150. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60151. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60152. */
  60153. var BoneAxesViewer = /** @class */ (function (_super) {
  60154. __extends(BoneAxesViewer, _super);
  60155. /**
  60156. * Creates a new BoneAxesViewer
  60157. * @param scene defines the hosting scene
  60158. * @param bone defines the target bone
  60159. * @param mesh defines the target mesh
  60160. * @param scaleLines defines a scaling factor for line length (1 by default)
  60161. */
  60162. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60163. if (scaleLines === void 0) { scaleLines = 1; }
  60164. var _this = _super.call(this, scene, scaleLines) || this;
  60165. /** Gets current position */
  60166. _this.pos = BABYLON.Vector3.Zero();
  60167. /** Gets direction of X axis */
  60168. _this.xaxis = BABYLON.Vector3.Zero();
  60169. /** Gets direction of Y axis */
  60170. _this.yaxis = BABYLON.Vector3.Zero();
  60171. /** Gets direction of Z axis */
  60172. _this.zaxis = BABYLON.Vector3.Zero();
  60173. _this.mesh = mesh;
  60174. _this.bone = bone;
  60175. return _this;
  60176. }
  60177. /**
  60178. * Force the viewer to update
  60179. */
  60180. BoneAxesViewer.prototype.update = function () {
  60181. if (!this.mesh || !this.bone) {
  60182. return;
  60183. }
  60184. var bone = this.bone;
  60185. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60186. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60187. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60188. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60189. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60190. };
  60191. /** Releases resources */
  60192. BoneAxesViewer.prototype.dispose = function () {
  60193. if (this.mesh) {
  60194. this.mesh = null;
  60195. this.bone = null;
  60196. _super.prototype.dispose.call(this);
  60197. }
  60198. };
  60199. return BoneAxesViewer;
  60200. }(Debug.AxesViewer));
  60201. Debug.BoneAxesViewer = BoneAxesViewer;
  60202. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60203. })(BABYLON || (BABYLON = {}));
  60204. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60205. var BABYLON;
  60206. (function (BABYLON) {
  60207. var RayHelper = /** @class */ (function () {
  60208. function RayHelper(ray) {
  60209. this.ray = ray;
  60210. }
  60211. RayHelper.CreateAndShow = function (ray, scene, color) {
  60212. var helper = new RayHelper(ray);
  60213. helper.show(scene, color);
  60214. return helper;
  60215. };
  60216. RayHelper.prototype.show = function (scene, color) {
  60217. if (!this._renderFunction && this.ray) {
  60218. var ray = this.ray;
  60219. this._renderFunction = this._render.bind(this);
  60220. this._scene = scene;
  60221. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60222. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60223. if (this._renderFunction) {
  60224. this._scene.registerBeforeRender(this._renderFunction);
  60225. }
  60226. }
  60227. if (color && this._renderLine) {
  60228. this._renderLine.color.copyFrom(color);
  60229. }
  60230. };
  60231. RayHelper.prototype.hide = function () {
  60232. if (this._renderFunction && this._scene) {
  60233. this._scene.unregisterBeforeRender(this._renderFunction);
  60234. this._scene = null;
  60235. this._renderFunction = null;
  60236. if (this._renderLine) {
  60237. this._renderLine.dispose();
  60238. this._renderLine = null;
  60239. }
  60240. this._renderPoints = [];
  60241. }
  60242. };
  60243. RayHelper.prototype._render = function () {
  60244. var ray = this.ray;
  60245. if (!ray) {
  60246. return;
  60247. }
  60248. var point = this._renderPoints[1];
  60249. var len = Math.min(ray.length, 1000000);
  60250. point.copyFrom(ray.direction);
  60251. point.scaleInPlace(len);
  60252. point.addInPlace(ray.origin);
  60253. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60254. };
  60255. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60256. this._attachedToMesh = mesh;
  60257. var ray = this.ray;
  60258. if (!ray) {
  60259. return;
  60260. }
  60261. if (!ray.direction) {
  60262. ray.direction = BABYLON.Vector3.Zero();
  60263. }
  60264. if (!ray.origin) {
  60265. ray.origin = BABYLON.Vector3.Zero();
  60266. }
  60267. if (length) {
  60268. ray.length = length;
  60269. }
  60270. if (!meshSpaceOrigin) {
  60271. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60272. }
  60273. if (!meshSpaceDirection) {
  60274. // -1 so that this will work with Mesh.lookAt
  60275. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60276. }
  60277. if (!this._meshSpaceDirection) {
  60278. this._meshSpaceDirection = meshSpaceDirection.clone();
  60279. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60280. }
  60281. else {
  60282. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60283. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60284. }
  60285. if (!this._updateToMeshFunction) {
  60286. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60287. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60288. }
  60289. this._updateToMesh();
  60290. };
  60291. RayHelper.prototype.detachFromMesh = function () {
  60292. if (this._attachedToMesh) {
  60293. if (this._updateToMeshFunction) {
  60294. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60295. }
  60296. this._attachedToMesh = null;
  60297. this._updateToMeshFunction = null;
  60298. }
  60299. };
  60300. RayHelper.prototype._updateToMesh = function () {
  60301. var ray = this.ray;
  60302. if (!this._attachedToMesh || !ray) {
  60303. return;
  60304. }
  60305. if (this._attachedToMesh._isDisposed) {
  60306. this.detachFromMesh();
  60307. return;
  60308. }
  60309. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60310. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60311. };
  60312. RayHelper.prototype.dispose = function () {
  60313. this.hide();
  60314. this.detachFromMesh();
  60315. this.ray = null;
  60316. };
  60317. return RayHelper;
  60318. }());
  60319. BABYLON.RayHelper = RayHelper;
  60320. })(BABYLON || (BABYLON = {}));
  60321. //# sourceMappingURL=babylon.rayHelper.js.map
  60322. var BABYLON;
  60323. (function (BABYLON) {
  60324. // load the inspector using require, if not present in the global namespace.
  60325. var DebugLayer = /** @class */ (function () {
  60326. function DebugLayer(scene) {
  60327. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60328. this.onPropertyChangedObservable = new BABYLON.Observable();
  60329. this._scene = scene;
  60330. }
  60331. /** Creates the inspector window. */
  60332. DebugLayer.prototype._createInspector = function (config) {
  60333. if (config === void 0) { config = {}; }
  60334. var popup = config.popup || false;
  60335. var initialTab = config.initialTab || 0;
  60336. var parentElement = config.parentElement || null;
  60337. if (!this._inspector) {
  60338. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60339. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60340. } // else nothing to do as instance is already created
  60341. };
  60342. DebugLayer.prototype.isVisible = function () {
  60343. if (!this._inspector) {
  60344. return false;
  60345. }
  60346. return true;
  60347. };
  60348. DebugLayer.prototype.hide = function () {
  60349. if (this._inspector) {
  60350. try {
  60351. this._inspector.dispose();
  60352. }
  60353. catch (e) {
  60354. // If the inspector has been removed directly from the inspector tool
  60355. }
  60356. this.onPropertyChangedObservable.clear();
  60357. this._inspector = null;
  60358. }
  60359. };
  60360. /**
  60361. *
  60362. * Launch the debugLayer.
  60363. *
  60364. * initialTab:
  60365. * | Value | Tab Name |
  60366. * | --- | --- |
  60367. * | 0 | Scene |
  60368. * | 1 | Console |
  60369. * | 2 | Stats |
  60370. * | 3 | Textures |
  60371. * | 4 | Mesh |
  60372. * | 5 | Light |
  60373. * | 6 | Material |
  60374. * | 7 | GLTF |
  60375. * | 8 | GUI |
  60376. * | 9 | Physics |
  60377. * | 10 | Camera |
  60378. * | 11 | Audio |
  60379. *
  60380. */
  60381. DebugLayer.prototype.show = function (config) {
  60382. if (config === void 0) { config = {}; }
  60383. if (typeof this.BJSINSPECTOR == 'undefined') {
  60384. // Load inspector and add it to the DOM
  60385. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60386. }
  60387. else {
  60388. // Otherwise creates the inspector
  60389. this._createInspector(config);
  60390. }
  60391. };
  60392. /**
  60393. * Gets the active tab
  60394. * @return the index of the active tab or -1 if the inspector is hidden
  60395. */
  60396. DebugLayer.prototype.getActiveTab = function () {
  60397. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60398. };
  60399. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60400. return DebugLayer;
  60401. }());
  60402. BABYLON.DebugLayer = DebugLayer;
  60403. })(BABYLON || (BABYLON = {}));
  60404. //# sourceMappingURL=babylon.debugLayer.js.map
  60405. var BABYLON;
  60406. (function (BABYLON) {
  60407. var Debug;
  60408. (function (Debug) {
  60409. /**
  60410. * Used to show the physics impostor around the specific mesh
  60411. */
  60412. var PhysicsViewer = /** @class */ (function () {
  60413. /**
  60414. * Creates a new PhysicsViewer
  60415. * @param scene defines the hosting scene
  60416. */
  60417. function PhysicsViewer(scene) {
  60418. /** @hidden */
  60419. this._impostors = [];
  60420. /** @hidden */
  60421. this._meshes = [];
  60422. /** @hidden */
  60423. this._numMeshes = 0;
  60424. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60425. var physicEngine = this._scene.getPhysicsEngine();
  60426. if (physicEngine) {
  60427. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60428. }
  60429. }
  60430. /** @hidden */
  60431. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60432. var plugin = this._physicsEnginePlugin;
  60433. for (var i = 0; i < this._numMeshes; i++) {
  60434. var impostor = this._impostors[i];
  60435. if (!impostor) {
  60436. continue;
  60437. }
  60438. if (impostor.isDisposed) {
  60439. this.hideImpostor(this._impostors[i--]);
  60440. }
  60441. else {
  60442. var mesh = this._meshes[i];
  60443. if (mesh && plugin) {
  60444. plugin.syncMeshWithImpostor(mesh, impostor);
  60445. }
  60446. }
  60447. }
  60448. };
  60449. /**
  60450. * Renders a specified physic impostor
  60451. * @param impostor defines the impostor to render
  60452. */
  60453. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60454. if (!this._scene) {
  60455. return;
  60456. }
  60457. for (var i = 0; i < this._numMeshes; i++) {
  60458. if (this._impostors[i] == impostor) {
  60459. return;
  60460. }
  60461. }
  60462. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60463. if (debugMesh) {
  60464. this._impostors[this._numMeshes] = impostor;
  60465. this._meshes[this._numMeshes] = debugMesh;
  60466. if (this._numMeshes === 0) {
  60467. this._renderFunction = this._updateDebugMeshes.bind(this);
  60468. this._scene.registerBeforeRender(this._renderFunction);
  60469. }
  60470. this._numMeshes++;
  60471. }
  60472. };
  60473. /**
  60474. * Hides a specified physic impostor
  60475. * @param impostor defines the impostor to hide
  60476. */
  60477. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60478. if (!impostor || !this._scene) {
  60479. return;
  60480. }
  60481. var removed = false;
  60482. for (var i = 0; i < this._numMeshes; i++) {
  60483. if (this._impostors[i] == impostor) {
  60484. var mesh = this._meshes[i];
  60485. if (!mesh) {
  60486. continue;
  60487. }
  60488. this._scene.removeMesh(mesh);
  60489. mesh.dispose();
  60490. this._numMeshes--;
  60491. if (this._numMeshes > 0) {
  60492. this._meshes[i] = this._meshes[this._numMeshes];
  60493. this._impostors[i] = this._impostors[this._numMeshes];
  60494. this._meshes[this._numMeshes] = null;
  60495. this._impostors[this._numMeshes] = null;
  60496. }
  60497. else {
  60498. this._meshes[0] = null;
  60499. this._impostors[0] = null;
  60500. }
  60501. removed = true;
  60502. break;
  60503. }
  60504. }
  60505. if (removed && this._numMeshes === 0) {
  60506. this._scene.unregisterBeforeRender(this._renderFunction);
  60507. }
  60508. };
  60509. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60510. if (!this._debugMaterial) {
  60511. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60512. this._debugMaterial.wireframe = true;
  60513. }
  60514. return this._debugMaterial;
  60515. };
  60516. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60517. if (!this._debugBoxMesh) {
  60518. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60519. this._debugBoxMesh.renderingGroupId = 1;
  60520. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60521. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60522. scene.removeMesh(this._debugBoxMesh);
  60523. }
  60524. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60525. };
  60526. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60527. if (!this._debugSphereMesh) {
  60528. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60529. this._debugSphereMesh.renderingGroupId = 1;
  60530. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60531. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60532. scene.removeMesh(this._debugSphereMesh);
  60533. }
  60534. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60535. };
  60536. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60537. var mesh = null;
  60538. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60539. mesh = this._getDebugBoxMesh(scene);
  60540. impostor.getBoxSizeToRef(mesh.scaling);
  60541. }
  60542. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60543. mesh = this._getDebugSphereMesh(scene);
  60544. var radius = impostor.getRadius();
  60545. mesh.scaling.x = radius * 2;
  60546. mesh.scaling.y = radius * 2;
  60547. mesh.scaling.z = radius * 2;
  60548. }
  60549. return mesh;
  60550. };
  60551. /** Releases all resources */
  60552. PhysicsViewer.prototype.dispose = function () {
  60553. for (var i = 0; i < this._numMeshes; i++) {
  60554. this.hideImpostor(this._impostors[i]);
  60555. }
  60556. if (this._debugBoxMesh) {
  60557. this._debugBoxMesh.dispose();
  60558. }
  60559. if (this._debugSphereMesh) {
  60560. this._debugSphereMesh.dispose();
  60561. }
  60562. if (this._debugMaterial) {
  60563. this._debugMaterial.dispose();
  60564. }
  60565. this._impostors.length = 0;
  60566. this._scene = null;
  60567. this._physicsEnginePlugin = null;
  60568. };
  60569. return PhysicsViewer;
  60570. }());
  60571. Debug.PhysicsViewer = PhysicsViewer;
  60572. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60573. })(BABYLON || (BABYLON = {}));
  60574. //# sourceMappingURL=babylon.physicsViewer.js.map
  60575. var BABYLON;
  60576. (function (BABYLON) {
  60577. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60578. get: function () {
  60579. return this._forceShowBoundingBoxes || false;
  60580. },
  60581. set: function (value) {
  60582. this._forceShowBoundingBoxes = value;
  60583. // Lazyly creates a BB renderer if needed.
  60584. if (value) {
  60585. this.getBoundingBoxRenderer();
  60586. }
  60587. },
  60588. enumerable: true,
  60589. configurable: true
  60590. });
  60591. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60592. if (!this._boundingBoxRenderer) {
  60593. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60594. }
  60595. return this._boundingBoxRenderer;
  60596. };
  60597. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60598. get: function () {
  60599. return this._showBoundingBox || false;
  60600. },
  60601. set: function (value) {
  60602. this._showBoundingBox = value;
  60603. // Lazyly creates a BB renderer if needed.
  60604. if (value) {
  60605. this.getScene().getBoundingBoxRenderer();
  60606. }
  60607. },
  60608. enumerable: true,
  60609. configurable: true
  60610. });
  60611. var BoundingBoxRenderer = /** @class */ (function () {
  60612. function BoundingBoxRenderer(scene) {
  60613. /**
  60614. * The component name helpfull to identify the component in the list of scene components.
  60615. */
  60616. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60617. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60618. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60619. this.showBackLines = true;
  60620. this.renderList = new BABYLON.SmartArray(32);
  60621. this._vertexBuffers = {};
  60622. this.scene = scene;
  60623. scene._addComponent(this);
  60624. }
  60625. /**
  60626. * Registers the component in a given scene
  60627. */
  60628. BoundingBoxRenderer.prototype.register = function () {
  60629. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60630. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60631. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60632. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60633. };
  60634. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60635. if (mesh.showSubMeshesBoundingBox) {
  60636. var boundingInfo = subMesh.getBoundingInfo();
  60637. if (boundingInfo !== null && boundingInfo !== undefined) {
  60638. this.renderList.push(boundingInfo.boundingBox);
  60639. }
  60640. }
  60641. };
  60642. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60643. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60644. var boundingInfo = sourceMesh.getBoundingInfo();
  60645. this.renderList.push(boundingInfo.boundingBox);
  60646. }
  60647. };
  60648. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60649. if (this._colorShader) {
  60650. return;
  60651. }
  60652. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60653. attributes: [BABYLON.VertexBuffer.PositionKind],
  60654. uniforms: ["world", "viewProjection", "color"]
  60655. });
  60656. var engine = this.scene.getEngine();
  60657. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60659. this._createIndexBuffer();
  60660. };
  60661. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60662. var engine = this.scene.getEngine();
  60663. 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]);
  60664. };
  60665. /**
  60666. * Rebuilds the elements related to this component in case of
  60667. * context lost for instance.
  60668. */
  60669. BoundingBoxRenderer.prototype.rebuild = function () {
  60670. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60671. if (vb) {
  60672. vb._rebuild();
  60673. }
  60674. this._createIndexBuffer();
  60675. };
  60676. BoundingBoxRenderer.prototype.reset = function () {
  60677. this.renderList.reset();
  60678. };
  60679. BoundingBoxRenderer.prototype.render = function () {
  60680. if (this.renderList.length === 0) {
  60681. return;
  60682. }
  60683. this._prepareRessources();
  60684. if (!this._colorShader.isReady()) {
  60685. return;
  60686. }
  60687. var engine = this.scene.getEngine();
  60688. engine.setDepthWrite(false);
  60689. this._colorShader._preBind();
  60690. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60691. var boundingBox = this.renderList.data[boundingBoxIndex];
  60692. var min = boundingBox.minimum;
  60693. var max = boundingBox.maximum;
  60694. var diff = max.subtract(min);
  60695. var median = min.add(diff.scale(0.5));
  60696. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60697. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60698. .multiply(boundingBox.getWorldMatrix());
  60699. // VBOs
  60700. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60701. if (this.showBackLines) {
  60702. // Back
  60703. engine.setDepthFunctionToGreaterOrEqual();
  60704. this.scene.resetCachedMaterial();
  60705. this._colorShader.setColor4("color", this.backColor.toColor4());
  60706. this._colorShader.bind(worldMatrix);
  60707. // Draw order
  60708. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60709. }
  60710. // Front
  60711. engine.setDepthFunctionToLess();
  60712. this.scene.resetCachedMaterial();
  60713. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60714. this._colorShader.bind(worldMatrix);
  60715. // Draw order
  60716. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60717. }
  60718. this._colorShader.unbind();
  60719. engine.setDepthFunctionToLessOrEqual();
  60720. engine.setDepthWrite(true);
  60721. };
  60722. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60723. this._prepareRessources();
  60724. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60725. return;
  60726. }
  60727. var engine = this.scene.getEngine();
  60728. engine.setDepthWrite(false);
  60729. engine.setColorWrite(false);
  60730. this._colorShader._preBind();
  60731. var boundingBox = mesh._boundingInfo.boundingBox;
  60732. var min = boundingBox.minimum;
  60733. var max = boundingBox.maximum;
  60734. var diff = max.subtract(min);
  60735. var median = min.add(diff.scale(0.5));
  60736. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60737. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60738. .multiply(boundingBox.getWorldMatrix());
  60739. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60740. engine.setDepthFunctionToLess();
  60741. this.scene.resetCachedMaterial();
  60742. this._colorShader.bind(worldMatrix);
  60743. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60744. this._colorShader.unbind();
  60745. engine.setDepthFunctionToLessOrEqual();
  60746. engine.setDepthWrite(true);
  60747. engine.setColorWrite(true);
  60748. };
  60749. BoundingBoxRenderer.prototype.dispose = function () {
  60750. if (!this._colorShader) {
  60751. return;
  60752. }
  60753. this.renderList.dispose();
  60754. this._colorShader.dispose();
  60755. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60756. if (buffer) {
  60757. buffer.dispose();
  60758. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60759. }
  60760. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60761. };
  60762. return BoundingBoxRenderer;
  60763. }());
  60764. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60765. })(BABYLON || (BABYLON = {}));
  60766. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60767. var BABYLON;
  60768. (function (BABYLON) {
  60769. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60770. return this._gl.createTransformFeedback();
  60771. };
  60772. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60773. this._gl.deleteTransformFeedback(value);
  60774. };
  60775. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60776. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60777. };
  60778. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60779. if (usePoints === void 0) { usePoints = true; }
  60780. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60781. };
  60782. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60783. this._gl.endTransformFeedback();
  60784. };
  60785. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60786. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60787. };
  60788. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60789. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60790. };
  60791. })(BABYLON || (BABYLON = {}));
  60792. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60793. var BABYLON;
  60794. (function (BABYLON) {
  60795. /**
  60796. * This represents a GPU particle system in Babylon
  60797. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60798. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60799. */
  60800. var GPUParticleSystem = /** @class */ (function (_super) {
  60801. __extends(GPUParticleSystem, _super);
  60802. /**
  60803. * Instantiates a GPU particle system.
  60804. * 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.
  60805. * @param name The name of the particle system
  60806. * @param options The options used to create the system
  60807. * @param scene The scene the particle system belongs to
  60808. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60809. */
  60810. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60811. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60812. var _this = _super.call(this, name) || this;
  60813. /**
  60814. * The layer mask we are rendering the particles through.
  60815. */
  60816. _this.layerMask = 0x0FFFFFFF;
  60817. _this._accumulatedCount = 0;
  60818. _this._targetIndex = 0;
  60819. _this._currentRenderId = -1;
  60820. _this._started = false;
  60821. _this._stopped = false;
  60822. _this._timeDelta = 0;
  60823. _this._attributesStrideSize = 21;
  60824. _this._actualFrame = 0;
  60825. _this._rawTextureWidth = 256;
  60826. /**
  60827. * An event triggered when the system is disposed.
  60828. */
  60829. _this.onDisposeObservable = new BABYLON.Observable();
  60830. /**
  60831. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60832. * to override the particles.
  60833. */
  60834. _this.forceDepthWrite = false;
  60835. _this._preWarmDone = false;
  60836. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60837. // Setup the default processing configuration to the scene.
  60838. _this._attachImageProcessingConfiguration(null);
  60839. _this._engine = _this._scene.getEngine();
  60840. if (!options.randomTextureSize) {
  60841. delete options.randomTextureSize;
  60842. }
  60843. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60844. var optionsAsNumber = options;
  60845. if (isFinite(optionsAsNumber)) {
  60846. fullOptions.capacity = optionsAsNumber;
  60847. }
  60848. _this._capacity = fullOptions.capacity;
  60849. _this._activeCount = fullOptions.capacity;
  60850. _this._currentActiveCount = 0;
  60851. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60852. _this._scene.particleSystems.push(_this);
  60853. _this._updateEffectOptions = {
  60854. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60855. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60856. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60857. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60858. uniformBuffersNames: [],
  60859. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60860. defines: "",
  60861. fallbacks: null,
  60862. onCompiled: null,
  60863. onError: null,
  60864. indexParameters: null,
  60865. maxSimultaneousLights: 0,
  60866. transformFeedbackVaryings: []
  60867. };
  60868. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60869. // Random data
  60870. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60871. var d = [];
  60872. for (var i = 0; i < maxTextureSize; ++i) {
  60873. d.push(Math.random());
  60874. d.push(Math.random());
  60875. d.push(Math.random());
  60876. d.push(Math.random());
  60877. }
  60878. _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);
  60879. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60880. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60881. d = [];
  60882. for (var i = 0; i < maxTextureSize; ++i) {
  60883. d.push(Math.random());
  60884. d.push(Math.random());
  60885. d.push(Math.random());
  60886. d.push(Math.random());
  60887. }
  60888. _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);
  60889. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60890. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60891. _this._randomTextureSize = maxTextureSize;
  60892. return _this;
  60893. }
  60894. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60895. /**
  60896. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60897. */
  60898. get: function () {
  60899. if (!BABYLON.Engine.LastCreatedEngine) {
  60900. return false;
  60901. }
  60902. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60903. },
  60904. enumerable: true,
  60905. configurable: true
  60906. });
  60907. /**
  60908. * Gets the maximum number of particles active at the same time.
  60909. * @returns The max number of active particles.
  60910. */
  60911. GPUParticleSystem.prototype.getCapacity = function () {
  60912. return this._capacity;
  60913. };
  60914. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60915. /**
  60916. * Gets or set the number of active particles
  60917. */
  60918. get: function () {
  60919. return this._activeCount;
  60920. },
  60921. set: function (value) {
  60922. this._activeCount = Math.min(value, this._capacity);
  60923. },
  60924. enumerable: true,
  60925. configurable: true
  60926. });
  60927. /**
  60928. * Is this system ready to be used/rendered
  60929. * @return true if the system is ready
  60930. */
  60931. GPUParticleSystem.prototype.isReady = function () {
  60932. if (!this._updateEffect) {
  60933. this._recreateUpdateEffect();
  60934. this._recreateRenderEffect();
  60935. return false;
  60936. }
  60937. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60938. return false;
  60939. }
  60940. return true;
  60941. };
  60942. /**
  60943. * Gets if the system has been started. (Note: this will still be true after stop is called)
  60944. * @returns True if it has been started, otherwise false.
  60945. */
  60946. GPUParticleSystem.prototype.isStarted = function () {
  60947. return this._started;
  60948. };
  60949. /**
  60950. * Starts the particle system and begins to emit
  60951. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60952. */
  60953. GPUParticleSystem.prototype.start = function (delay) {
  60954. var _this = this;
  60955. if (delay === void 0) { delay = 0; }
  60956. if (delay) {
  60957. setTimeout(function () {
  60958. _this.start(0);
  60959. }, delay);
  60960. return;
  60961. }
  60962. this._started = true;
  60963. this._stopped = false;
  60964. this._preWarmDone = false;
  60965. };
  60966. /**
  60967. * Stops the particle system.
  60968. */
  60969. GPUParticleSystem.prototype.stop = function () {
  60970. this._stopped = true;
  60971. };
  60972. /**
  60973. * Remove all active particles
  60974. */
  60975. GPUParticleSystem.prototype.reset = function () {
  60976. this._releaseBuffers();
  60977. this._releaseVAOs();
  60978. this._currentActiveCount = 0;
  60979. this._targetIndex = 0;
  60980. };
  60981. /**
  60982. * Returns the string "GPUParticleSystem"
  60983. * @returns a string containing the class name
  60984. */
  60985. GPUParticleSystem.prototype.getClassName = function () {
  60986. return "GPUParticleSystem";
  60987. };
  60988. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60989. if (!gradients) {
  60990. return this;
  60991. }
  60992. var index = 0;
  60993. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60994. var valueGradient = gradients_1[_i];
  60995. if (valueGradient.gradient === gradient) {
  60996. gradients.splice(index, 1);
  60997. break;
  60998. }
  60999. index++;
  61000. }
  61001. if (texture) {
  61002. texture.dispose();
  61003. }
  61004. this._releaseBuffers();
  61005. return this;
  61006. };
  61007. /**
  61008. * Adds a new color gradient
  61009. * @param gradient defines the gradient to use (between 0 and 1)
  61010. * @param color defines the color to affect to the specified gradient
  61011. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61012. * @returns the current particle system
  61013. */
  61014. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61015. if (!this._colorGradients) {
  61016. this._colorGradients = [];
  61017. }
  61018. var colorGradient = new BABYLON.ColorGradient();
  61019. colorGradient.gradient = gradient;
  61020. colorGradient.color1 = color1;
  61021. this._colorGradients.push(colorGradient);
  61022. this._colorGradients.sort(function (a, b) {
  61023. if (a.gradient < b.gradient) {
  61024. return -1;
  61025. }
  61026. else if (a.gradient > b.gradient) {
  61027. return 1;
  61028. }
  61029. return 0;
  61030. });
  61031. if (this._colorGradientsTexture) {
  61032. this._colorGradientsTexture.dispose();
  61033. this._colorGradientsTexture = null;
  61034. }
  61035. this._releaseBuffers();
  61036. return this;
  61037. };
  61038. /**
  61039. * Remove a specific color gradient
  61040. * @param gradient defines the gradient to remove
  61041. * @returns the current particle system
  61042. */
  61043. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61044. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  61045. this._colorGradientsTexture = null;
  61046. return this;
  61047. };
  61048. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61049. var valueGradient = new BABYLON.FactorGradient();
  61050. valueGradient.gradient = gradient;
  61051. valueGradient.factor1 = factor;
  61052. factorGradients.push(valueGradient);
  61053. factorGradients.sort(function (a, b) {
  61054. if (a.gradient < b.gradient) {
  61055. return -1;
  61056. }
  61057. else if (a.gradient > b.gradient) {
  61058. return 1;
  61059. }
  61060. return 0;
  61061. });
  61062. this._releaseBuffers();
  61063. };
  61064. /**
  61065. * Adds a new size gradient
  61066. * @param gradient defines the gradient to use (between 0 and 1)
  61067. * @param factor defines the size factor to affect to the specified gradient
  61068. * @returns the current particle system
  61069. */
  61070. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61071. if (!this._sizeGradients) {
  61072. this._sizeGradients = [];
  61073. }
  61074. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61075. if (this._sizeGradientsTexture) {
  61076. this._sizeGradientsTexture.dispose();
  61077. this._sizeGradientsTexture = null;
  61078. }
  61079. this._releaseBuffers();
  61080. return this;
  61081. };
  61082. /**
  61083. * Remove a specific size gradient
  61084. * @param gradient defines the gradient to remove
  61085. * @returns the current particle system
  61086. */
  61087. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61088. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61089. this._sizeGradientsTexture = null;
  61090. return this;
  61091. };
  61092. /**
  61093. * Adds a new angular speed gradient
  61094. * @param gradient defines the gradient to use (between 0 and 1)
  61095. * @param factor defines the angular speed to affect to the specified gradient
  61096. * @returns the current particle system
  61097. */
  61098. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61099. if (!this._angularSpeedGradients) {
  61100. this._angularSpeedGradients = [];
  61101. }
  61102. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61103. if (this._angularSpeedGradientsTexture) {
  61104. this._angularSpeedGradientsTexture.dispose();
  61105. this._angularSpeedGradientsTexture = null;
  61106. }
  61107. this._releaseBuffers();
  61108. return this;
  61109. };
  61110. /**
  61111. * Remove a specific angular speed gradient
  61112. * @param gradient defines the gradient to remove
  61113. * @returns the current particle system
  61114. */
  61115. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61116. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61117. this._angularSpeedGradientsTexture = null;
  61118. return this;
  61119. };
  61120. /**
  61121. * Adds a new velocity gradient
  61122. * @param gradient defines the gradient to use (between 0 and 1)
  61123. * @param factor defines the velocity to affect to the specified gradient
  61124. * @returns the current particle system
  61125. */
  61126. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61127. if (!this._velocityGradients) {
  61128. this._velocityGradients = [];
  61129. }
  61130. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61131. if (this._velocityGradientsTexture) {
  61132. this._velocityGradientsTexture.dispose();
  61133. this._velocityGradientsTexture = null;
  61134. }
  61135. this._releaseBuffers();
  61136. return this;
  61137. };
  61138. /**
  61139. * Remove a specific velocity gradient
  61140. * @param gradient defines the gradient to remove
  61141. * @returns the current particle system
  61142. */
  61143. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61144. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61145. this._velocityGradientsTexture = null;
  61146. return this;
  61147. };
  61148. /**
  61149. * Adds a new limit velocity gradient
  61150. * @param gradient defines the gradient to use (between 0 and 1)
  61151. * @param factor defines the limit velocity value to affect to the specified gradient
  61152. * @returns the current particle system
  61153. */
  61154. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61155. if (!this._limitVelocityGradients) {
  61156. this._limitVelocityGradients = [];
  61157. }
  61158. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61159. if (this._limitVelocityGradientsTexture) {
  61160. this._limitVelocityGradientsTexture.dispose();
  61161. this._limitVelocityGradientsTexture = null;
  61162. }
  61163. this._releaseBuffers();
  61164. return this;
  61165. };
  61166. /**
  61167. * Remove a specific limit velocity gradient
  61168. * @param gradient defines the gradient to remove
  61169. * @returns the current particle system
  61170. */
  61171. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61172. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61173. this._limitVelocityGradientsTexture = null;
  61174. return this;
  61175. };
  61176. /**
  61177. * Adds a new drag gradient
  61178. * @param gradient defines the gradient to use (between 0 and 1)
  61179. * @param factor defines the drag value to affect to the specified gradient
  61180. * @returns the current particle system
  61181. */
  61182. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61183. if (!this._dragGradients) {
  61184. this._dragGradients = [];
  61185. }
  61186. this._addFactorGradient(this._dragGradients, gradient, factor);
  61187. if (this._dragGradientsTexture) {
  61188. this._dragGradientsTexture.dispose();
  61189. this._dragGradientsTexture = null;
  61190. }
  61191. this._releaseBuffers();
  61192. return this;
  61193. };
  61194. /**
  61195. * Remove a specific drag gradient
  61196. * @param gradient defines the gradient to remove
  61197. * @returns the current particle system
  61198. */
  61199. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61200. this._removeGradient(gradient, this._dragGradients, this._dragGradientsTexture);
  61201. this._dragGradientsTexture = null;
  61202. return this;
  61203. };
  61204. GPUParticleSystem.prototype._reset = function () {
  61205. this._releaseBuffers();
  61206. };
  61207. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  61208. var updateVertexBuffers = {};
  61209. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  61210. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  61211. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  61212. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  61213. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  61214. var offset = 12;
  61215. if (!this._colorGradientsTexture) {
  61216. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  61217. offset += 4;
  61218. }
  61219. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  61220. offset += 3;
  61221. if (!this._isBillboardBased) {
  61222. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  61223. offset += 3;
  61224. }
  61225. if (this._angularSpeedGradientsTexture) {
  61226. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  61227. offset += 1;
  61228. }
  61229. else {
  61230. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  61231. offset += 2;
  61232. }
  61233. if (this._isAnimationSheetEnabled) {
  61234. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  61235. offset += 1;
  61236. }
  61237. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  61238. this._engine.bindArrayBuffer(null);
  61239. return vao;
  61240. };
  61241. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  61242. var renderVertexBuffers = {};
  61243. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61244. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61245. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61246. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61247. var offset = 12;
  61248. if (!this._colorGradientsTexture) {
  61249. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61250. offset += 4;
  61251. }
  61252. offset += 3; // Direction
  61253. if (!this._isBillboardBased) {
  61254. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61255. offset += 3;
  61256. }
  61257. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61258. if (this._angularSpeedGradientsTexture) {
  61259. offset++;
  61260. }
  61261. else {
  61262. offset += 2;
  61263. }
  61264. if (this._isAnimationSheetEnabled) {
  61265. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61266. offset += 1;
  61267. }
  61268. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61269. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61270. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61271. this._engine.bindArrayBuffer(null);
  61272. return vao;
  61273. };
  61274. GPUParticleSystem.prototype._initialize = function (force) {
  61275. if (force === void 0) { force = false; }
  61276. if (this._buffer0 && !force) {
  61277. return;
  61278. }
  61279. var engine = this._scene.getEngine();
  61280. var data = new Array();
  61281. if (!this.isBillboardBased) {
  61282. this._attributesStrideSize += 3;
  61283. }
  61284. if (this._colorGradientsTexture) {
  61285. this._attributesStrideSize -= 4;
  61286. }
  61287. if (this._angularSpeedGradientsTexture) {
  61288. this._attributesStrideSize -= 1;
  61289. }
  61290. if (this._isAnimationSheetEnabled) {
  61291. this._attributesStrideSize += 1;
  61292. }
  61293. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61294. // position
  61295. data.push(0.0);
  61296. data.push(0.0);
  61297. data.push(0.0);
  61298. // Age and life
  61299. data.push(0.0); // create the particle as a dead one to create a new one at start
  61300. data.push(0.0);
  61301. // Seed
  61302. data.push(Math.random());
  61303. data.push(Math.random());
  61304. data.push(Math.random());
  61305. data.push(Math.random());
  61306. // Size
  61307. data.push(0.0);
  61308. data.push(0.0);
  61309. data.push(0.0);
  61310. if (!this._colorGradientsTexture) {
  61311. // color
  61312. data.push(0.0);
  61313. data.push(0.0);
  61314. data.push(0.0);
  61315. data.push(0.0);
  61316. }
  61317. // direction
  61318. data.push(0.0);
  61319. data.push(0.0);
  61320. data.push(0.0);
  61321. if (!this.isBillboardBased) {
  61322. // initialDirection
  61323. data.push(0.0);
  61324. data.push(0.0);
  61325. data.push(0.0);
  61326. }
  61327. // angle
  61328. data.push(0.0);
  61329. if (!this._angularSpeedGradientsTexture) {
  61330. data.push(0.0);
  61331. }
  61332. if (this._isAnimationSheetEnabled) {
  61333. data.push(0.0);
  61334. }
  61335. }
  61336. // Sprite data
  61337. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61338. -0.5, 0.5, 0, 1,
  61339. -0.5, -0.5, 0, 0,
  61340. 0.5, -0.5, 1, 0]);
  61341. // Buffers
  61342. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61343. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61344. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61345. // Update VAO
  61346. this._updateVAO = [];
  61347. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61348. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61349. // Render VAO
  61350. this._renderVAO = [];
  61351. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61352. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61353. // Links
  61354. this._sourceBuffer = this._buffer0;
  61355. this._targetBuffer = this._buffer1;
  61356. };
  61357. /** @hidden */
  61358. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61359. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61360. if (this._isBillboardBased) {
  61361. defines += "\n#define BILLBOARD";
  61362. }
  61363. if (this._colorGradientsTexture) {
  61364. defines += "\n#define COLORGRADIENTS";
  61365. }
  61366. if (this._sizeGradientsTexture) {
  61367. defines += "\n#define SIZEGRADIENTS";
  61368. }
  61369. if (this._angularSpeedGradientsTexture) {
  61370. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61371. }
  61372. if (this._velocityGradientsTexture) {
  61373. defines += "\n#define VELOCITYGRADIENTS";
  61374. }
  61375. if (this.isAnimationSheetEnabled) {
  61376. defines += "\n#define ANIMATESHEET";
  61377. }
  61378. if (this.noiseTexture) {
  61379. defines += "\n#define NOISE";
  61380. }
  61381. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61382. return;
  61383. }
  61384. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61385. if (!this._colorGradientsTexture) {
  61386. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61387. }
  61388. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61389. if (!this._isBillboardBased) {
  61390. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61391. }
  61392. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61393. if (this.isAnimationSheetEnabled) {
  61394. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61395. }
  61396. this._updateEffectOptions.defines = defines;
  61397. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61398. };
  61399. /** @hidden */
  61400. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61401. var defines = "";
  61402. if (this._scene.clipPlane) {
  61403. defines = "\n#define CLIPPLANE";
  61404. }
  61405. if (this._scene.clipPlane2) {
  61406. defines = "\n#define CLIPPLANE2";
  61407. }
  61408. if (this._scene.clipPlane3) {
  61409. defines = "\n#define CLIPPLANE3";
  61410. }
  61411. if (this._scene.clipPlane4) {
  61412. defines = "\n#define CLIPPLANE4";
  61413. }
  61414. if (this._isBillboardBased) {
  61415. defines += "\n#define BILLBOARD";
  61416. switch (this.billboardMode) {
  61417. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61418. defines += "\n#define BILLBOARDY";
  61419. break;
  61420. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61421. default:
  61422. break;
  61423. }
  61424. }
  61425. if (this._colorGradientsTexture) {
  61426. defines += "\n#define COLORGRADIENTS";
  61427. }
  61428. if (this.isAnimationSheetEnabled) {
  61429. defines += "\n#define ANIMATESHEET";
  61430. }
  61431. if (this._imageProcessingConfiguration) {
  61432. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61433. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61434. }
  61435. if (this._renderEffect && this._renderEffect.defines === defines) {
  61436. return;
  61437. }
  61438. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61439. var samplers = ["textureSampler", "colorGradientSampler"];
  61440. if (BABYLON.ImageProcessingConfiguration) {
  61441. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61442. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61443. }
  61444. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61445. };
  61446. /**
  61447. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61448. * @param preWarm defines if we are in the pre-warmimg phase
  61449. */
  61450. GPUParticleSystem.prototype.animate = function (preWarm) {
  61451. if (preWarm === void 0) { preWarm = false; }
  61452. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61453. this._actualFrame += this._timeDelta;
  61454. if (!this._stopped) {
  61455. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61456. this.stop();
  61457. }
  61458. }
  61459. };
  61460. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61461. var texture = this[textureName];
  61462. if (!factorGradients || !factorGradients.length || texture) {
  61463. return;
  61464. }
  61465. var data = new Float32Array(this._rawTextureWidth);
  61466. for (var x = 0; x < this._rawTextureWidth; x++) {
  61467. var ratio = x / this._rawTextureWidth;
  61468. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61469. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61470. });
  61471. }
  61472. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61473. };
  61474. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61475. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61476. };
  61477. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61478. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61479. };
  61480. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61481. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61482. };
  61483. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61484. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61485. return;
  61486. }
  61487. var data = new Uint8Array(this._rawTextureWidth * 4);
  61488. var tmpColor = BABYLON.Tmp.Color4[0];
  61489. for (var x = 0; x < this._rawTextureWidth; x++) {
  61490. var ratio = x / this._rawTextureWidth;
  61491. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61492. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61493. data[x * 4] = tmpColor.r * 255;
  61494. data[x * 4 + 1] = tmpColor.g * 255;
  61495. data[x * 4 + 2] = tmpColor.b * 255;
  61496. data[x * 4 + 3] = tmpColor.a * 255;
  61497. });
  61498. }
  61499. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61500. };
  61501. /**
  61502. * Renders the particle system in its current state
  61503. * @param preWarm defines if the system should only update the particles but not render them
  61504. * @returns the current number of particles
  61505. */
  61506. GPUParticleSystem.prototype.render = function (preWarm) {
  61507. if (preWarm === void 0) { preWarm = false; }
  61508. if (!this._started) {
  61509. return 0;
  61510. }
  61511. this._createColorGradientTexture();
  61512. this._createSizeGradientTexture();
  61513. this._createAngularSpeedGradientTexture();
  61514. this._createVelocityGradientTexture();
  61515. this._recreateUpdateEffect();
  61516. this._recreateRenderEffect();
  61517. if (!this.isReady()) {
  61518. return 0;
  61519. }
  61520. if (!preWarm) {
  61521. if (!this._preWarmDone && this.preWarmCycles) {
  61522. for (var index = 0; index < this.preWarmCycles; index++) {
  61523. this.animate(true);
  61524. this.render(true);
  61525. }
  61526. this._preWarmDone = true;
  61527. }
  61528. if (this._currentRenderId === this._scene.getRenderId()) {
  61529. return 0;
  61530. }
  61531. this._currentRenderId = this._scene.getRenderId();
  61532. }
  61533. // Get everything ready to render
  61534. this._initialize();
  61535. this._accumulatedCount += this.emitRate * this._timeDelta;
  61536. if (this._accumulatedCount > 1) {
  61537. var intPart = this._accumulatedCount | 0;
  61538. this._accumulatedCount -= intPart;
  61539. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61540. }
  61541. if (!this._currentActiveCount) {
  61542. return 0;
  61543. }
  61544. // Enable update effect
  61545. this._engine.enableEffect(this._updateEffect);
  61546. this._engine.setState(false);
  61547. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61548. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61549. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61550. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61551. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61552. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61553. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61554. if (!this._colorGradientsTexture) {
  61555. this._updateEffect.setDirectColor4("color1", this.color1);
  61556. this._updateEffect.setDirectColor4("color2", this.color2);
  61557. }
  61558. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61559. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61560. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61561. this._updateEffect.setVector3("gravity", this.gravity);
  61562. if (this._sizeGradientsTexture) {
  61563. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61564. }
  61565. if (this._angularSpeedGradientsTexture) {
  61566. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61567. }
  61568. if (this._velocityGradientsTexture) {
  61569. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61570. }
  61571. if (this.particleEmitterType) {
  61572. this.particleEmitterType.applyToShader(this._updateEffect);
  61573. }
  61574. if (this._isAnimationSheetEnabled) {
  61575. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61576. }
  61577. if (this.noiseTexture) {
  61578. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61579. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61580. }
  61581. var emitterWM;
  61582. if (this.emitter.position) {
  61583. var emitterMesh = this.emitter;
  61584. emitterWM = emitterMesh.getWorldMatrix();
  61585. }
  61586. else {
  61587. var emitterPosition = this.emitter;
  61588. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61589. }
  61590. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61591. // Bind source VAO
  61592. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61593. // Update
  61594. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61595. this._engine.setRasterizerState(false);
  61596. this._engine.beginTransformFeedback(true);
  61597. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61598. this._engine.endTransformFeedback();
  61599. this._engine.setRasterizerState(true);
  61600. this._engine.bindTransformFeedbackBuffer(null);
  61601. if (!preWarm) {
  61602. // Enable render effect
  61603. this._engine.enableEffect(this._renderEffect);
  61604. var viewMatrix = this._scene.getViewMatrix();
  61605. this._renderEffect.setMatrix("view", viewMatrix);
  61606. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61607. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61608. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61609. if (this._colorGradientsTexture) {
  61610. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61611. }
  61612. else {
  61613. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61614. }
  61615. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61616. var baseSize = this.particleTexture.getBaseSize();
  61617. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61618. }
  61619. if (this._isBillboardBased) {
  61620. var camera = this._scene.activeCamera;
  61621. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61622. }
  61623. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61624. var invView = viewMatrix.clone();
  61625. invView.invert();
  61626. this._renderEffect.setMatrix("invView", invView);
  61627. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  61628. }
  61629. // image processing
  61630. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61631. this._imageProcessingConfiguration.bind(this._renderEffect);
  61632. }
  61633. // Draw order
  61634. switch (this.blendMode) {
  61635. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61636. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61637. break;
  61638. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61639. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61640. break;
  61641. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61642. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61643. break;
  61644. }
  61645. if (this.forceDepthWrite) {
  61646. this._engine.setDepthWrite(true);
  61647. }
  61648. // Bind source VAO
  61649. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61650. // Render
  61651. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61652. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61653. }
  61654. // Switch VAOs
  61655. this._targetIndex++;
  61656. if (this._targetIndex === 2) {
  61657. this._targetIndex = 0;
  61658. }
  61659. // Switch buffers
  61660. var tmpBuffer = this._sourceBuffer;
  61661. this._sourceBuffer = this._targetBuffer;
  61662. this._targetBuffer = tmpBuffer;
  61663. return this._currentActiveCount;
  61664. };
  61665. /**
  61666. * Rebuilds the particle system
  61667. */
  61668. GPUParticleSystem.prototype.rebuild = function () {
  61669. this._initialize(true);
  61670. };
  61671. GPUParticleSystem.prototype._releaseBuffers = function () {
  61672. if (this._buffer0) {
  61673. this._buffer0.dispose();
  61674. this._buffer0 = null;
  61675. }
  61676. if (this._buffer1) {
  61677. this._buffer1.dispose();
  61678. this._buffer1 = null;
  61679. }
  61680. if (this._spriteBuffer) {
  61681. this._spriteBuffer.dispose();
  61682. this._spriteBuffer = null;
  61683. }
  61684. };
  61685. GPUParticleSystem.prototype._releaseVAOs = function () {
  61686. if (!this._updateVAO) {
  61687. return;
  61688. }
  61689. for (var index = 0; index < this._updateVAO.length; index++) {
  61690. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61691. }
  61692. this._updateVAO = [];
  61693. for (var index = 0; index < this._renderVAO.length; index++) {
  61694. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61695. }
  61696. this._renderVAO = [];
  61697. };
  61698. /**
  61699. * Disposes the particle system and free the associated resources
  61700. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61701. */
  61702. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61703. if (disposeTexture === void 0) { disposeTexture = true; }
  61704. var index = this._scene.particleSystems.indexOf(this);
  61705. if (index > -1) {
  61706. this._scene.particleSystems.splice(index, 1);
  61707. }
  61708. this._releaseBuffers();
  61709. this._releaseVAOs();
  61710. if (this._colorGradientsTexture) {
  61711. this._colorGradientsTexture.dispose();
  61712. this._colorGradientsTexture = null;
  61713. }
  61714. if (this._sizeGradientsTexture) {
  61715. this._sizeGradientsTexture.dispose();
  61716. this._sizeGradientsTexture = null;
  61717. }
  61718. if (this._angularSpeedGradientsTexture) {
  61719. this._angularSpeedGradientsTexture.dispose();
  61720. this._angularSpeedGradientsTexture = null;
  61721. }
  61722. if (this._velocityGradientsTexture) {
  61723. this._velocityGradientsTexture.dispose();
  61724. this._velocityGradientsTexture = null;
  61725. }
  61726. if (this._limitVelocityGradientsTexture) {
  61727. this._limitVelocityGradientsTexture.dispose();
  61728. this._limitVelocityGradientsTexture = null;
  61729. }
  61730. if (this._randomTexture) {
  61731. this._randomTexture.dispose();
  61732. this._randomTexture = null;
  61733. }
  61734. if (this._randomTexture2) {
  61735. this._randomTexture2.dispose();
  61736. this._randomTexture2 = null;
  61737. }
  61738. if (disposeTexture && this.particleTexture) {
  61739. this.particleTexture.dispose();
  61740. this.particleTexture = null;
  61741. }
  61742. if (disposeTexture && this.noiseTexture) {
  61743. this.noiseTexture.dispose();
  61744. this.noiseTexture = null;
  61745. }
  61746. // Callback
  61747. this.onDisposeObservable.notifyObservers(this);
  61748. this.onDisposeObservable.clear();
  61749. };
  61750. /**
  61751. * Clones the particle system.
  61752. * @param name The name of the cloned object
  61753. * @param newEmitter The new emitter to use
  61754. * @returns the cloned particle system
  61755. */
  61756. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61757. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61758. BABYLON.Tools.DeepCopy(this, result);
  61759. if (newEmitter === undefined) {
  61760. newEmitter = this.emitter;
  61761. }
  61762. result.emitter = newEmitter;
  61763. if (this.particleTexture) {
  61764. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61765. }
  61766. return result;
  61767. };
  61768. /**
  61769. * Serializes the particle system to a JSON object.
  61770. * @returns the JSON object
  61771. */
  61772. GPUParticleSystem.prototype.serialize = function () {
  61773. var serializationObject = {};
  61774. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61775. serializationObject.activeParticleCount = this.activeParticleCount;
  61776. return serializationObject;
  61777. };
  61778. /**
  61779. * Parses a JSON object to create a GPU particle system.
  61780. * @param parsedParticleSystem The JSON object to parse
  61781. * @param scene The scene to create the particle system in
  61782. * @param rootUrl The root url to use to load external dependencies like texture
  61783. * @returns the parsed GPU particle system
  61784. */
  61785. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61786. var name = parsedParticleSystem.name;
  61787. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61788. if (parsedParticleSystem.activeParticleCount) {
  61789. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61790. }
  61791. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61792. return particleSystem;
  61793. };
  61794. return GPUParticleSystem;
  61795. }(BABYLON.BaseParticleSystem));
  61796. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61797. })(BABYLON || (BABYLON = {}));
  61798. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61799. var BABYLON;
  61800. (function (BABYLON) {
  61801. /**
  61802. * Represents one particle of a solid particle system.
  61803. */
  61804. var SolidParticle = /** @class */ (function () {
  61805. /**
  61806. * Creates a Solid Particle object.
  61807. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61808. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61809. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61810. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61811. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61812. * @param shapeId (integer) is the model shape identifier in the SPS.
  61813. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61814. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61815. */
  61816. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61817. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61818. /**
  61819. * particle global index
  61820. */
  61821. this.idx = 0;
  61822. /**
  61823. * The color of the particle
  61824. */
  61825. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61826. /**
  61827. * The world space position of the particle.
  61828. */
  61829. this.position = BABYLON.Vector3.Zero();
  61830. /**
  61831. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61832. */
  61833. this.rotation = BABYLON.Vector3.Zero();
  61834. /**
  61835. * The scaling of the particle.
  61836. */
  61837. this.scaling = BABYLON.Vector3.One();
  61838. /**
  61839. * The uvs of the particle.
  61840. */
  61841. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61842. /**
  61843. * The current speed of the particle.
  61844. */
  61845. this.velocity = BABYLON.Vector3.Zero();
  61846. /**
  61847. * The pivot point in the particle local space.
  61848. */
  61849. this.pivot = BABYLON.Vector3.Zero();
  61850. /**
  61851. * Must the particle be translated from its pivot point in its local space ?
  61852. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61853. * Default : false
  61854. */
  61855. this.translateFromPivot = false;
  61856. /**
  61857. * Is the particle active or not ?
  61858. */
  61859. this.alive = true;
  61860. /**
  61861. * Is the particle visible or not ?
  61862. */
  61863. this.isVisible = true;
  61864. /**
  61865. * Index of this particle in the global "positions" array (Internal use)
  61866. * @hidden
  61867. */
  61868. this._pos = 0;
  61869. /**
  61870. * @hidden Index of this particle in the global "indices" array (Internal use)
  61871. */
  61872. this._ind = 0;
  61873. /**
  61874. * ModelShape id of this particle
  61875. */
  61876. this.shapeId = 0;
  61877. /**
  61878. * Index of the particle in its shape id (Internal use)
  61879. */
  61880. this.idxInShape = 0;
  61881. /**
  61882. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  61883. */
  61884. this._stillInvisible = false;
  61885. /**
  61886. * @hidden Last computed particle rotation matrix
  61887. */
  61888. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61889. /**
  61890. * Parent particle Id, if any.
  61891. * Default null.
  61892. */
  61893. this.parentId = null;
  61894. /**
  61895. * @hidden Internal global position in the SPS.
  61896. */
  61897. this._globalPosition = BABYLON.Vector3.Zero();
  61898. this.idx = particleIndex;
  61899. this._pos = positionIndex;
  61900. this._ind = indiceIndex;
  61901. this._model = model;
  61902. this.shapeId = shapeId;
  61903. this.idxInShape = idxInShape;
  61904. this._sps = sps;
  61905. if (modelBoundingInfo) {
  61906. this._modelBoundingInfo = modelBoundingInfo;
  61907. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61908. }
  61909. }
  61910. Object.defineProperty(SolidParticle.prototype, "scale", {
  61911. /**
  61912. * Legacy support, changed scale to scaling
  61913. */
  61914. get: function () {
  61915. return this.scaling;
  61916. },
  61917. /**
  61918. * Legacy support, changed scale to scaling
  61919. */
  61920. set: function (scale) {
  61921. this.scaling = scale;
  61922. },
  61923. enumerable: true,
  61924. configurable: true
  61925. });
  61926. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61927. /**
  61928. * Legacy support, changed quaternion to rotationQuaternion
  61929. */
  61930. get: function () {
  61931. return this.rotationQuaternion;
  61932. },
  61933. /**
  61934. * Legacy support, changed quaternion to rotationQuaternion
  61935. */
  61936. set: function (q) {
  61937. this.rotationQuaternion = q;
  61938. },
  61939. enumerable: true,
  61940. configurable: true
  61941. });
  61942. /**
  61943. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61944. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61945. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61946. * @returns true if it intersects
  61947. */
  61948. SolidParticle.prototype.intersectsMesh = function (target) {
  61949. if (!this._boundingInfo || !target._boundingInfo) {
  61950. return false;
  61951. }
  61952. if (this._sps._bSphereOnly) {
  61953. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61954. }
  61955. return this._boundingInfo.intersects(target._boundingInfo, false);
  61956. };
  61957. return SolidParticle;
  61958. }());
  61959. BABYLON.SolidParticle = SolidParticle;
  61960. /**
  61961. * Represents the shape of the model used by one particle of a solid particle system.
  61962. * SPS internal tool, don't use it manually.
  61963. */
  61964. var ModelShape = /** @class */ (function () {
  61965. /**
  61966. * 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.
  61967. * SPS internal tool, don't use it manually.
  61968. * @hidden
  61969. */
  61970. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61971. /**
  61972. * length of the shape in the model indices array (internal use)
  61973. * @hidden
  61974. */
  61975. this._indicesLength = 0;
  61976. this.shapeID = id;
  61977. this._shape = shape;
  61978. this._indicesLength = indicesLength;
  61979. this._shapeUV = shapeUV;
  61980. this._positionFunction = posFunction;
  61981. this._vertexFunction = vtxFunction;
  61982. }
  61983. return ModelShape;
  61984. }());
  61985. BABYLON.ModelShape = ModelShape;
  61986. /**
  61987. * Represents a Depth Sorted Particle in the solid particle system.
  61988. */
  61989. var DepthSortedParticle = /** @class */ (function () {
  61990. function DepthSortedParticle() {
  61991. /**
  61992. * Index of the particle in the "indices" array
  61993. */
  61994. this.ind = 0;
  61995. /**
  61996. * Length of the particle shape in the "indices" array
  61997. */
  61998. this.indicesLength = 0;
  61999. /**
  62000. * Squared distance from the particle to the camera
  62001. */
  62002. this.sqDistance = 0.0;
  62003. }
  62004. return DepthSortedParticle;
  62005. }());
  62006. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62007. })(BABYLON || (BABYLON = {}));
  62008. //# sourceMappingURL=babylon.solidParticle.js.map
  62009. var BABYLON;
  62010. (function (BABYLON) {
  62011. /**
  62012. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62013. *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.
  62014. * The SPS is also a particle system. It provides some methods to manage the particles.
  62015. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62016. *
  62017. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62018. */
  62019. var SolidParticleSystem = /** @class */ (function () {
  62020. /**
  62021. * Creates a SPS (Solid Particle System) object.
  62022. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62023. * @param scene (Scene) is the scene in which the SPS is added.
  62024. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62025. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62026. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62027. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62028. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62029. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62030. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62031. */
  62032. function SolidParticleSystem(name, scene, options) {
  62033. /**
  62034. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62035. * Example : var p = SPS.particles[i];
  62036. */
  62037. this.particles = new Array();
  62038. /**
  62039. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62040. */
  62041. this.nbParticles = 0;
  62042. /**
  62043. * If the particles must ever face the camera (default false). Useful for planar particles.
  62044. */
  62045. this.billboard = false;
  62046. /**
  62047. * Recompute normals when adding a shape
  62048. */
  62049. this.recomputeNormals = true;
  62050. /**
  62051. * This a counter ofr your own usage. It's not set by any SPS functions.
  62052. */
  62053. this.counter = 0;
  62054. /**
  62055. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62056. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62057. */
  62058. this.vars = {};
  62059. /**
  62060. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62061. * @hidden
  62062. */
  62063. this._bSphereOnly = false;
  62064. /**
  62065. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62066. * @hidden
  62067. */
  62068. this._bSphereRadiusFactor = 1.0;
  62069. this._positions = new Array();
  62070. this._indices = new Array();
  62071. this._normals = new Array();
  62072. this._colors = new Array();
  62073. this._uvs = new Array();
  62074. this._index = 0; // indices index
  62075. this._updatable = true;
  62076. this._pickable = false;
  62077. this._isVisibilityBoxLocked = false;
  62078. this._alwaysVisible = false;
  62079. this._depthSort = false;
  62080. this._shapeCounter = 0;
  62081. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62082. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62083. this._computeParticleColor = true;
  62084. this._computeParticleTexture = true;
  62085. this._computeParticleRotation = true;
  62086. this._computeParticleVertex = false;
  62087. this._computeBoundingBox = false;
  62088. this._depthSortParticles = true;
  62089. this._cam_axisZ = BABYLON.Vector3.Zero();
  62090. this._cam_axisY = BABYLON.Vector3.Zero();
  62091. this._cam_axisX = BABYLON.Vector3.Zero();
  62092. this._axisZ = BABYLON.Axis.Z;
  62093. this._camDir = BABYLON.Vector3.Zero();
  62094. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62095. this._rotMatrix = new BABYLON.Matrix();
  62096. this._invertMatrix = new BABYLON.Matrix();
  62097. this._rotated = BABYLON.Vector3.Zero();
  62098. this._quaternion = new BABYLON.Quaternion();
  62099. this._vertex = BABYLON.Vector3.Zero();
  62100. this._normal = BABYLON.Vector3.Zero();
  62101. this._yaw = 0.0;
  62102. this._pitch = 0.0;
  62103. this._roll = 0.0;
  62104. this._halfroll = 0.0;
  62105. this._halfpitch = 0.0;
  62106. this._halfyaw = 0.0;
  62107. this._sinRoll = 0.0;
  62108. this._cosRoll = 0.0;
  62109. this._sinPitch = 0.0;
  62110. this._cosPitch = 0.0;
  62111. this._sinYaw = 0.0;
  62112. this._cosYaw = 0.0;
  62113. this._mustUnrotateFixedNormals = false;
  62114. this._minimum = BABYLON.Vector3.Zero();
  62115. this._maximum = BABYLON.Vector3.Zero();
  62116. this._minBbox = BABYLON.Vector3.Zero();
  62117. this._maxBbox = BABYLON.Vector3.Zero();
  62118. this._particlesIntersect = false;
  62119. this._depthSortFunction = function (p1, p2) {
  62120. return (p2.sqDistance - p1.sqDistance);
  62121. };
  62122. this._needs32Bits = false;
  62123. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62124. this._scaledPivot = BABYLON.Vector3.Zero();
  62125. this._particleHasParent = false;
  62126. this.name = name;
  62127. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62128. this._camera = scene.activeCamera;
  62129. this._pickable = options ? options.isPickable : false;
  62130. this._depthSort = options ? options.enableDepthSort : false;
  62131. this._particlesIntersect = options ? options.particleIntersection : false;
  62132. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62133. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62134. if (options && options.updatable !== undefined) {
  62135. this._updatable = options.updatable;
  62136. }
  62137. else {
  62138. this._updatable = true;
  62139. }
  62140. if (this._pickable) {
  62141. this.pickedParticles = [];
  62142. }
  62143. if (this._depthSort) {
  62144. this.depthSortedParticles = [];
  62145. }
  62146. }
  62147. /**
  62148. * Builds the SPS underlying mesh. Returns a standard Mesh.
  62149. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  62150. * @returns the created mesh
  62151. */
  62152. SolidParticleSystem.prototype.buildMesh = function () {
  62153. if (this.nbParticles === 0) {
  62154. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  62155. this.addShape(triangle, 1);
  62156. triangle.dispose();
  62157. }
  62158. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  62159. this._positions32 = new Float32Array(this._positions);
  62160. this._uvs32 = new Float32Array(this._uvs);
  62161. this._colors32 = new Float32Array(this._colors);
  62162. if (this.recomputeNormals) {
  62163. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  62164. }
  62165. this._normals32 = new Float32Array(this._normals);
  62166. this._fixedNormal32 = new Float32Array(this._normals);
  62167. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  62168. this._unrotateFixedNormals();
  62169. }
  62170. var vertexData = new BABYLON.VertexData();
  62171. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  62172. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  62173. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  62174. if (this._uvs32.length > 0) {
  62175. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  62176. }
  62177. if (this._colors32.length > 0) {
  62178. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  62179. }
  62180. var mesh = new BABYLON.Mesh(this.name, this._scene);
  62181. vertexData.applyToMesh(mesh, this._updatable);
  62182. this.mesh = mesh;
  62183. this.mesh.isPickable = this._pickable;
  62184. // free memory
  62185. if (!this._depthSort) {
  62186. this._indices = null;
  62187. }
  62188. this._positions = null;
  62189. this._normals = null;
  62190. this._uvs = null;
  62191. this._colors = null;
  62192. if (!this._updatable) {
  62193. this.particles.length = 0;
  62194. }
  62195. return mesh;
  62196. };
  62197. /**
  62198. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  62199. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  62200. * Thus the particles generated from `digest()` have their property `position` set yet.
  62201. * @param mesh ( Mesh ) is the mesh to be digested
  62202. * @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
  62203. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  62204. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  62205. * @returns the current SPS
  62206. */
  62207. SolidParticleSystem.prototype.digest = function (mesh, options) {
  62208. var size = (options && options.facetNb) || 1;
  62209. var number = (options && options.number) || 0;
  62210. var delta = (options && options.delta) || 0;
  62211. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62212. var meshInd = mesh.getIndices();
  62213. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62214. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62215. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62216. var f = 0; // facet counter
  62217. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  62218. // compute size from number
  62219. if (number) {
  62220. number = (number > totalFacets) ? totalFacets : number;
  62221. size = Math.round(totalFacets / number);
  62222. delta = 0;
  62223. }
  62224. else {
  62225. size = (size > totalFacets) ? totalFacets : size;
  62226. }
  62227. var facetPos = []; // submesh positions
  62228. var facetInd = []; // submesh indices
  62229. var facetUV = []; // submesh UV
  62230. var facetCol = []; // submesh colors
  62231. var barycenter = BABYLON.Vector3.Zero();
  62232. var sizeO = size;
  62233. while (f < totalFacets) {
  62234. size = sizeO + Math.floor((1 + delta) * Math.random());
  62235. if (f > totalFacets - size) {
  62236. size = totalFacets - f;
  62237. }
  62238. // reset temp arrays
  62239. facetPos.length = 0;
  62240. facetInd.length = 0;
  62241. facetUV.length = 0;
  62242. facetCol.length = 0;
  62243. // iterate over "size" facets
  62244. var fi = 0;
  62245. for (var j = f * 3; j < (f + size) * 3; j++) {
  62246. facetInd.push(fi);
  62247. var i = meshInd[j];
  62248. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62249. if (meshUV) {
  62250. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62251. }
  62252. if (meshCol) {
  62253. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62254. }
  62255. fi++;
  62256. }
  62257. // create a model shape for each single particle
  62258. var idx = this.nbParticles;
  62259. var shape = this._posToShape(facetPos);
  62260. var shapeUV = this._uvsToShapeUV(facetUV);
  62261. // compute the barycenter of the shape
  62262. var v;
  62263. for (v = 0; v < shape.length; v++) {
  62264. barycenter.addInPlace(shape[v]);
  62265. }
  62266. barycenter.scaleInPlace(1 / shape.length);
  62267. // shift the shape from its barycenter to the origin
  62268. for (v = 0; v < shape.length; v++) {
  62269. shape[v].subtractInPlace(barycenter);
  62270. }
  62271. var bInfo;
  62272. if (this._particlesIntersect) {
  62273. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62274. }
  62275. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62276. // add the particle in the SPS
  62277. var currentPos = this._positions.length;
  62278. var currentInd = this._indices.length;
  62279. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62280. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62281. // initialize the particle position
  62282. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62283. this._index += shape.length;
  62284. idx++;
  62285. this.nbParticles++;
  62286. this._shapeCounter++;
  62287. f += size;
  62288. }
  62289. return this;
  62290. };
  62291. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62292. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62293. var index = 0;
  62294. var idx = 0;
  62295. for (var p = 0; p < this.particles.length; p++) {
  62296. this._particle = this.particles[p];
  62297. this._shape = this._particle._model._shape;
  62298. if (this._particle.rotationQuaternion) {
  62299. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62300. }
  62301. else {
  62302. this._yaw = this._particle.rotation.y;
  62303. this._pitch = this._particle.rotation.x;
  62304. this._roll = this._particle.rotation.z;
  62305. this._quaternionRotationYPR();
  62306. }
  62307. this._quaternionToRotationMatrix();
  62308. this._rotMatrix.invertToRef(this._invertMatrix);
  62309. for (var pt = 0; pt < this._shape.length; pt++) {
  62310. idx = index + pt * 3;
  62311. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62312. this._fixedNormal32[idx] = this._normal.x;
  62313. this._fixedNormal32[idx + 1] = this._normal.y;
  62314. this._fixedNormal32[idx + 2] = this._normal.z;
  62315. }
  62316. index = idx + 3;
  62317. }
  62318. };
  62319. //reset copy
  62320. SolidParticleSystem.prototype._resetCopy = function () {
  62321. this._copy.position.x = 0;
  62322. this._copy.position.y = 0;
  62323. this._copy.position.z = 0;
  62324. this._copy.rotation.x = 0;
  62325. this._copy.rotation.y = 0;
  62326. this._copy.rotation.z = 0;
  62327. this._copy.rotationQuaternion = null;
  62328. this._copy.scaling.x = 1.0;
  62329. this._copy.scaling.y = 1.0;
  62330. this._copy.scaling.z = 1.0;
  62331. this._copy.uvs.x = 0;
  62332. this._copy.uvs.y = 0;
  62333. this._copy.uvs.z = 1.0;
  62334. this._copy.uvs.w = 1.0;
  62335. this._copy.color = null;
  62336. this._copy.translateFromPivot = false;
  62337. };
  62338. // _meshBuilder : inserts the shape model in the global SPS mesh
  62339. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62340. var i;
  62341. var u = 0;
  62342. var c = 0;
  62343. var n = 0;
  62344. this._resetCopy();
  62345. if (options && options.positionFunction) { // call to custom positionFunction
  62346. options.positionFunction(this._copy, idx, idxInShape);
  62347. this._mustUnrotateFixedNormals = true;
  62348. }
  62349. if (this._copy.rotationQuaternion) {
  62350. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62351. }
  62352. else {
  62353. this._yaw = this._copy.rotation.y;
  62354. this._pitch = this._copy.rotation.x;
  62355. this._roll = this._copy.rotation.z;
  62356. this._quaternionRotationYPR();
  62357. }
  62358. this._quaternionToRotationMatrix();
  62359. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62360. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62361. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62362. if (this._copy.translateFromPivot) {
  62363. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62364. }
  62365. else {
  62366. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62367. }
  62368. for (i = 0; i < shape.length; i++) {
  62369. this._vertex.x = shape[i].x;
  62370. this._vertex.y = shape[i].y;
  62371. this._vertex.z = shape[i].z;
  62372. if (options && options.vertexFunction) {
  62373. options.vertexFunction(this._copy, this._vertex, i);
  62374. }
  62375. this._vertex.x *= this._copy.scaling.x;
  62376. this._vertex.y *= this._copy.scaling.y;
  62377. this._vertex.z *= this._copy.scaling.z;
  62378. this._vertex.x -= this._scaledPivot.x;
  62379. this._vertex.y -= this._scaledPivot.y;
  62380. this._vertex.z -= this._scaledPivot.z;
  62381. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62382. this._rotated.addInPlace(this._pivotBackTranslation);
  62383. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62384. if (meshUV) {
  62385. 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);
  62386. u += 2;
  62387. }
  62388. if (this._copy.color) {
  62389. this._color = this._copy.color;
  62390. }
  62391. else if (meshCol && meshCol[c] !== undefined) {
  62392. this._color.r = meshCol[c];
  62393. this._color.g = meshCol[c + 1];
  62394. this._color.b = meshCol[c + 2];
  62395. this._color.a = meshCol[c + 3];
  62396. }
  62397. else {
  62398. this._color.r = 1.0;
  62399. this._color.g = 1.0;
  62400. this._color.b = 1.0;
  62401. this._color.a = 1.0;
  62402. }
  62403. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62404. c += 4;
  62405. if (!this.recomputeNormals && meshNor) {
  62406. this._normal.x = meshNor[n];
  62407. this._normal.y = meshNor[n + 1];
  62408. this._normal.z = meshNor[n + 2];
  62409. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62410. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62411. n += 3;
  62412. }
  62413. }
  62414. for (i = 0; i < meshInd.length; i++) {
  62415. var current_ind = p + meshInd[i];
  62416. indices.push(current_ind);
  62417. if (current_ind > 65535) {
  62418. this._needs32Bits = true;
  62419. }
  62420. }
  62421. if (this._pickable) {
  62422. var nbfaces = meshInd.length / 3;
  62423. for (i = 0; i < nbfaces; i++) {
  62424. this.pickedParticles.push({ idx: idx, faceId: i });
  62425. }
  62426. }
  62427. if (this._depthSort) {
  62428. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62429. }
  62430. return this._copy;
  62431. };
  62432. // returns a shape array from positions array
  62433. SolidParticleSystem.prototype._posToShape = function (positions) {
  62434. var shape = [];
  62435. for (var i = 0; i < positions.length; i += 3) {
  62436. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62437. }
  62438. return shape;
  62439. };
  62440. // returns a shapeUV array from a Vector4 uvs
  62441. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62442. var shapeUV = [];
  62443. if (uvs) {
  62444. for (var i = 0; i < uvs.length; i++)
  62445. shapeUV.push(uvs[i]);
  62446. }
  62447. return shapeUV;
  62448. };
  62449. // adds a new particle object in the particles array
  62450. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62451. if (bInfo === void 0) { bInfo = null; }
  62452. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62453. this.particles.push(sp);
  62454. return sp;
  62455. };
  62456. /**
  62457. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62458. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62459. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62460. * @param nb (positive integer) the number of particles to be created from this model
  62461. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62462. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62463. * @returns the number of shapes in the system
  62464. */
  62465. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62466. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62467. var meshInd = mesh.getIndices();
  62468. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62469. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62470. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62471. var bbInfo;
  62472. if (this._particlesIntersect) {
  62473. bbInfo = mesh.getBoundingInfo();
  62474. }
  62475. var shape = this._posToShape(meshPos);
  62476. var shapeUV = this._uvsToShapeUV(meshUV);
  62477. var posfunc = options ? options.positionFunction : null;
  62478. var vtxfunc = options ? options.vertexFunction : null;
  62479. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62480. // particles
  62481. var sp;
  62482. var currentCopy;
  62483. var idx = this.nbParticles;
  62484. for (var i = 0; i < nb; i++) {
  62485. var currentPos = this._positions.length;
  62486. var currentInd = this._indices.length;
  62487. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62488. if (this._updatable) {
  62489. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62490. sp.position.copyFrom(currentCopy.position);
  62491. sp.rotation.copyFrom(currentCopy.rotation);
  62492. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62493. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62494. }
  62495. if (currentCopy.color && sp.color) {
  62496. sp.color.copyFrom(currentCopy.color);
  62497. }
  62498. sp.scaling.copyFrom(currentCopy.scaling);
  62499. sp.uvs.copyFrom(currentCopy.uvs);
  62500. }
  62501. this._index += shape.length;
  62502. idx++;
  62503. }
  62504. this.nbParticles += nb;
  62505. this._shapeCounter++;
  62506. return this._shapeCounter - 1;
  62507. };
  62508. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62509. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62510. this._resetCopy();
  62511. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62512. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62513. }
  62514. if (this._copy.rotationQuaternion) {
  62515. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62516. }
  62517. else {
  62518. this._yaw = this._copy.rotation.y;
  62519. this._pitch = this._copy.rotation.x;
  62520. this._roll = this._copy.rotation.z;
  62521. this._quaternionRotationYPR();
  62522. }
  62523. this._quaternionToRotationMatrix();
  62524. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62525. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62526. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62527. if (this._copy.translateFromPivot) {
  62528. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62529. }
  62530. else {
  62531. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62532. }
  62533. this._shape = particle._model._shape;
  62534. for (var pt = 0; pt < this._shape.length; pt++) {
  62535. this._vertex.x = this._shape[pt].x;
  62536. this._vertex.y = this._shape[pt].y;
  62537. this._vertex.z = this._shape[pt].z;
  62538. if (particle._model._vertexFunction) {
  62539. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62540. }
  62541. this._vertex.x *= this._copy.scaling.x;
  62542. this._vertex.y *= this._copy.scaling.y;
  62543. this._vertex.z *= this._copy.scaling.z;
  62544. this._vertex.x -= this._scaledPivot.x;
  62545. this._vertex.y -= this._scaledPivot.y;
  62546. this._vertex.z -= this._scaledPivot.z;
  62547. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62548. this._rotated.addInPlace(this._pivotBackTranslation);
  62549. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62550. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62551. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62552. }
  62553. particle.position.x = 0.0;
  62554. particle.position.y = 0.0;
  62555. particle.position.z = 0.0;
  62556. particle.rotation.x = 0.0;
  62557. particle.rotation.y = 0.0;
  62558. particle.rotation.z = 0.0;
  62559. particle.rotationQuaternion = null;
  62560. particle.scaling.x = 1.0;
  62561. particle.scaling.y = 1.0;
  62562. particle.scaling.z = 1.0;
  62563. particle.uvs.x = 0.0;
  62564. particle.uvs.y = 0.0;
  62565. particle.uvs.z = 1.0;
  62566. particle.uvs.w = 1.0;
  62567. particle.pivot.x = 0.0;
  62568. particle.pivot.y = 0.0;
  62569. particle.pivot.z = 0.0;
  62570. particle.translateFromPivot = false;
  62571. particle.parentId = null;
  62572. };
  62573. /**
  62574. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62575. * @returns the SPS.
  62576. */
  62577. SolidParticleSystem.prototype.rebuildMesh = function () {
  62578. for (var p = 0; p < this.particles.length; p++) {
  62579. this._rebuildParticle(this.particles[p]);
  62580. }
  62581. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62582. return this;
  62583. };
  62584. /**
  62585. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62586. * This method calls `updateParticle()` for each particle of the SPS.
  62587. * For an animated SPS, it is usually called within the render loop.
  62588. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62589. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62590. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62591. * @returns the SPS.
  62592. */
  62593. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62594. if (start === void 0) { start = 0; }
  62595. if (end === void 0) { end = this.nbParticles - 1; }
  62596. if (update === void 0) { update = true; }
  62597. if (!this._updatable) {
  62598. return this;
  62599. }
  62600. // custom beforeUpdate
  62601. this.beforeUpdateParticles(start, end, update);
  62602. this._cam_axisX.x = 1.0;
  62603. this._cam_axisX.y = 0.0;
  62604. this._cam_axisX.z = 0.0;
  62605. this._cam_axisY.x = 0.0;
  62606. this._cam_axisY.y = 1.0;
  62607. this._cam_axisY.z = 0.0;
  62608. this._cam_axisZ.x = 0.0;
  62609. this._cam_axisZ.y = 0.0;
  62610. this._cam_axisZ.z = 1.0;
  62611. // cases when the World Matrix is to be computed first
  62612. if (this.billboard || this._depthSort) {
  62613. this.mesh.computeWorldMatrix(true);
  62614. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62615. }
  62616. // if the particles will always face the camera
  62617. if (this.billboard) {
  62618. // compute the camera position and un-rotate it by the current mesh rotation
  62619. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62620. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62621. this._cam_axisZ.normalize();
  62622. // same for camera up vector extracted from the cam view matrix
  62623. var view = this._camera.getViewMatrix(true);
  62624. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62625. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62626. this._cam_axisY.normalize();
  62627. this._cam_axisX.normalize();
  62628. }
  62629. // if depthSort, compute the camera global position in the mesh local system
  62630. if (this._depthSort) {
  62631. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62632. }
  62633. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62634. var idx = 0; // current position index in the global array positions32
  62635. var index = 0; // position start index in the global array positions32 of the current particle
  62636. var colidx = 0; // current color index in the global array colors32
  62637. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62638. var uvidx = 0; // current uv index in the global array uvs32
  62639. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62640. var pt = 0; // current index in the particle model shape
  62641. if (this.mesh.isFacetDataEnabled) {
  62642. this._computeBoundingBox = true;
  62643. }
  62644. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62645. if (this._computeBoundingBox) {
  62646. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62647. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62648. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62649. }
  62650. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62651. if (this.mesh._boundingInfo) {
  62652. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62653. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62654. }
  62655. }
  62656. }
  62657. // particle loop
  62658. index = this.particles[start]._pos;
  62659. var vpos = (index / 3) | 0;
  62660. colorIndex = vpos * 4;
  62661. uvIndex = vpos * 2;
  62662. for (var p = start; p <= end; p++) {
  62663. this._particle = this.particles[p];
  62664. this._shape = this._particle._model._shape;
  62665. this._shapeUV = this._particle._model._shapeUV;
  62666. // call to custom user function to update the particle properties
  62667. this.updateParticle(this._particle);
  62668. // camera-particle distance for depth sorting
  62669. if (this._depthSort && this._depthSortParticles) {
  62670. var dsp = this.depthSortedParticles[p];
  62671. dsp.ind = this._particle._ind;
  62672. dsp.indicesLength = this._particle._model._indicesLength;
  62673. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62674. }
  62675. // skip the computations for inactive or already invisible particles
  62676. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62677. // increment indexes for the next particle
  62678. pt = this._shape.length;
  62679. index += pt * 3;
  62680. colorIndex += pt * 4;
  62681. uvIndex += pt * 2;
  62682. continue;
  62683. }
  62684. if (this._particle.isVisible) {
  62685. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62686. this._particleHasParent = (this._particle.parentId !== null);
  62687. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62688. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62689. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62690. // particle rotation matrix
  62691. if (this.billboard) {
  62692. this._particle.rotation.x = 0.0;
  62693. this._particle.rotation.y = 0.0;
  62694. }
  62695. if (this._computeParticleRotation || this.billboard) {
  62696. if (this._particle.rotationQuaternion) {
  62697. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62698. }
  62699. else {
  62700. this._yaw = this._particle.rotation.y;
  62701. this._pitch = this._particle.rotation.x;
  62702. this._roll = this._particle.rotation.z;
  62703. this._quaternionRotationYPR();
  62704. }
  62705. this._quaternionToRotationMatrix();
  62706. }
  62707. if (this._particleHasParent) {
  62708. this._parent = this.particles[this._particle.parentId];
  62709. 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];
  62710. 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];
  62711. 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];
  62712. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62713. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62714. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62715. if (this._computeParticleRotation || this.billboard) {
  62716. 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];
  62717. 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];
  62718. 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];
  62719. 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];
  62720. 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];
  62721. 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];
  62722. 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];
  62723. 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];
  62724. 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];
  62725. }
  62726. }
  62727. else {
  62728. this._particle._globalPosition.x = this._particle.position.x;
  62729. this._particle._globalPosition.y = this._particle.position.y;
  62730. this._particle._globalPosition.z = this._particle.position.z;
  62731. if (this._computeParticleRotation || this.billboard) {
  62732. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62733. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62734. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62735. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62736. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62737. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62738. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62739. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62740. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62741. }
  62742. }
  62743. if (this._particle.translateFromPivot) {
  62744. this._pivotBackTranslation.x = 0.0;
  62745. this._pivotBackTranslation.y = 0.0;
  62746. this._pivotBackTranslation.z = 0.0;
  62747. }
  62748. else {
  62749. this._pivotBackTranslation.x = this._scaledPivot.x;
  62750. this._pivotBackTranslation.y = this._scaledPivot.y;
  62751. this._pivotBackTranslation.z = this._scaledPivot.z;
  62752. }
  62753. // particle vertex loop
  62754. for (pt = 0; pt < this._shape.length; pt++) {
  62755. idx = index + pt * 3;
  62756. colidx = colorIndex + pt * 4;
  62757. uvidx = uvIndex + pt * 2;
  62758. this._vertex.x = this._shape[pt].x;
  62759. this._vertex.y = this._shape[pt].y;
  62760. this._vertex.z = this._shape[pt].z;
  62761. if (this._computeParticleVertex) {
  62762. this.updateParticleVertex(this._particle, this._vertex, pt);
  62763. }
  62764. // positions
  62765. this._vertex.x *= this._particle.scaling.x;
  62766. this._vertex.y *= this._particle.scaling.y;
  62767. this._vertex.z *= this._particle.scaling.z;
  62768. this._vertex.x -= this._scaledPivot.x;
  62769. this._vertex.y -= this._scaledPivot.y;
  62770. this._vertex.z -= this._scaledPivot.z;
  62771. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62772. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62773. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62774. this._rotated.x += this._pivotBackTranslation.x;
  62775. this._rotated.y += this._pivotBackTranslation.y;
  62776. this._rotated.z += this._pivotBackTranslation.z;
  62777. 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;
  62778. 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;
  62779. 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;
  62780. if (this._computeBoundingBox) {
  62781. if (this._positions32[idx] < this._minimum.x) {
  62782. this._minimum.x = this._positions32[idx];
  62783. }
  62784. if (this._positions32[idx] > this._maximum.x) {
  62785. this._maximum.x = this._positions32[idx];
  62786. }
  62787. if (this._positions32[idx + 1] < this._minimum.y) {
  62788. this._minimum.y = this._positions32[idx + 1];
  62789. }
  62790. if (this._positions32[idx + 1] > this._maximum.y) {
  62791. this._maximum.y = this._positions32[idx + 1];
  62792. }
  62793. if (this._positions32[idx + 2] < this._minimum.z) {
  62794. this._minimum.z = this._positions32[idx + 2];
  62795. }
  62796. if (this._positions32[idx + 2] > this._maximum.z) {
  62797. this._maximum.z = this._positions32[idx + 2];
  62798. }
  62799. }
  62800. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62801. if (!this._computeParticleVertex) {
  62802. this._normal.x = this._fixedNormal32[idx];
  62803. this._normal.y = this._fixedNormal32[idx + 1];
  62804. this._normal.z = this._fixedNormal32[idx + 2];
  62805. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62806. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62807. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62808. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62809. 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;
  62810. 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;
  62811. }
  62812. if (this._computeParticleColor && this._particle.color) {
  62813. this._colors32[colidx] = this._particle.color.r;
  62814. this._colors32[colidx + 1] = this._particle.color.g;
  62815. this._colors32[colidx + 2] = this._particle.color.b;
  62816. this._colors32[colidx + 3] = this._particle.color.a;
  62817. }
  62818. if (this._computeParticleTexture) {
  62819. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62820. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62821. }
  62822. }
  62823. }
  62824. // particle just set invisible : scaled to zero and positioned at the origin
  62825. else {
  62826. this._particle._stillInvisible = true; // mark the particle as invisible
  62827. for (pt = 0; pt < this._shape.length; pt++) {
  62828. idx = index + pt * 3;
  62829. colidx = colorIndex + pt * 4;
  62830. uvidx = uvIndex + pt * 2;
  62831. this._positions32[idx] = 0.0;
  62832. this._positions32[idx + 1] = 0.0;
  62833. this._positions32[idx + 2] = 0.0;
  62834. this._normals32[idx] = 0.0;
  62835. this._normals32[idx + 1] = 0.0;
  62836. this._normals32[idx + 2] = 0.0;
  62837. if (this._computeParticleColor && this._particle.color) {
  62838. this._colors32[colidx] = this._particle.color.r;
  62839. this._colors32[colidx + 1] = this._particle.color.g;
  62840. this._colors32[colidx + 2] = this._particle.color.b;
  62841. this._colors32[colidx + 3] = this._particle.color.a;
  62842. }
  62843. if (this._computeParticleTexture) {
  62844. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62845. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62846. }
  62847. }
  62848. }
  62849. // if the particle intersections must be computed : update the bbInfo
  62850. if (this._particlesIntersect) {
  62851. var bInfo = this._particle._boundingInfo;
  62852. var bBox = bInfo.boundingBox;
  62853. var bSphere = bInfo.boundingSphere;
  62854. if (!this._bSphereOnly) {
  62855. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62856. for (var b = 0; b < bBox.vectors.length; b++) {
  62857. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62858. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62859. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62860. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62861. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62862. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62863. 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;
  62864. 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;
  62865. 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;
  62866. }
  62867. bBox._update(this.mesh._worldMatrix);
  62868. }
  62869. // place and scale the particle bouding sphere in the SPS local system, then update it
  62870. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62871. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62872. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62873. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62874. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62875. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62876. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62877. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62878. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62879. 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));
  62880. bSphere._update(this.mesh._worldMatrix);
  62881. }
  62882. // increment indexes for the next particle
  62883. index = idx + 3;
  62884. colorIndex = colidx + 4;
  62885. uvIndex = uvidx + 2;
  62886. }
  62887. // if the VBO must be updated
  62888. if (update) {
  62889. if (this._computeParticleColor) {
  62890. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62891. }
  62892. if (this._computeParticleTexture) {
  62893. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62894. }
  62895. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62896. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62897. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62898. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62899. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62900. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62901. for (var i = 0; i < this._normals32.length; i++) {
  62902. this._fixedNormal32[i] = this._normals32[i];
  62903. }
  62904. }
  62905. if (!this.mesh.areNormalsFrozen) {
  62906. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62907. }
  62908. }
  62909. if (this._depthSort && this._depthSortParticles) {
  62910. this.depthSortedParticles.sort(this._depthSortFunction);
  62911. var dspl = this.depthSortedParticles.length;
  62912. var sorted = 0;
  62913. var lind = 0;
  62914. var sind = 0;
  62915. var sid = 0;
  62916. for (sorted = 0; sorted < dspl; sorted++) {
  62917. lind = this.depthSortedParticles[sorted].indicesLength;
  62918. sind = this.depthSortedParticles[sorted].ind;
  62919. for (var i = 0; i < lind; i++) {
  62920. this._indices32[sid] = this._indices[sind + i];
  62921. sid++;
  62922. }
  62923. }
  62924. this.mesh.updateIndices(this._indices32);
  62925. }
  62926. }
  62927. if (this._computeBoundingBox) {
  62928. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62929. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62930. }
  62931. this.afterUpdateParticles(start, end, update);
  62932. return this;
  62933. };
  62934. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62935. this._halfroll = this._roll * 0.5;
  62936. this._halfpitch = this._pitch * 0.5;
  62937. this._halfyaw = this._yaw * 0.5;
  62938. this._sinRoll = Math.sin(this._halfroll);
  62939. this._cosRoll = Math.cos(this._halfroll);
  62940. this._sinPitch = Math.sin(this._halfpitch);
  62941. this._cosPitch = Math.cos(this._halfpitch);
  62942. this._sinYaw = Math.sin(this._halfyaw);
  62943. this._cosYaw = Math.cos(this._halfyaw);
  62944. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62945. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62946. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62947. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62948. };
  62949. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62950. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62951. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62952. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62953. this._rotMatrix.m[3] = 0;
  62954. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62955. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62956. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62957. this._rotMatrix.m[7] = 0;
  62958. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62959. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62960. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62961. this._rotMatrix.m[11] = 0;
  62962. this._rotMatrix.m[12] = 0;
  62963. this._rotMatrix.m[13] = 0;
  62964. this._rotMatrix.m[14] = 0;
  62965. this._rotMatrix.m[15] = 1.0;
  62966. };
  62967. /**
  62968. * Disposes the SPS.
  62969. */
  62970. SolidParticleSystem.prototype.dispose = function () {
  62971. this.mesh.dispose();
  62972. this.vars = null;
  62973. // drop references to internal big arrays for the GC
  62974. this._positions = null;
  62975. this._indices = null;
  62976. this._normals = null;
  62977. this._uvs = null;
  62978. this._colors = null;
  62979. this._indices32 = null;
  62980. this._positions32 = null;
  62981. this._normals32 = null;
  62982. this._fixedNormal32 = null;
  62983. this._uvs32 = null;
  62984. this._colors32 = null;
  62985. this.pickedParticles = null;
  62986. };
  62987. /**
  62988. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62989. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62990. * @returns the SPS.
  62991. */
  62992. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62993. if (!this._isVisibilityBoxLocked) {
  62994. this.mesh.refreshBoundingInfo();
  62995. }
  62996. return this;
  62997. };
  62998. /**
  62999. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63000. * @param size the size (float) of the visibility box
  63001. * note : this doesn't lock the SPS mesh bounding box.
  63002. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63003. */
  63004. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63005. var vis = size / 2;
  63006. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63007. };
  63008. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63009. /**
  63010. * Gets whether the SPS as always visible or not
  63011. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63012. */
  63013. get: function () {
  63014. return this._alwaysVisible;
  63015. },
  63016. /**
  63017. * Sets the SPS as always visible or not
  63018. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63019. */
  63020. set: function (val) {
  63021. this._alwaysVisible = val;
  63022. this.mesh.alwaysSelectAsActiveMesh = val;
  63023. },
  63024. enumerable: true,
  63025. configurable: true
  63026. });
  63027. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63028. /**
  63029. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63030. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63031. */
  63032. get: function () {
  63033. return this._isVisibilityBoxLocked;
  63034. },
  63035. /**
  63036. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63037. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63038. */
  63039. set: function (val) {
  63040. this._isVisibilityBoxLocked = val;
  63041. var boundingInfo = this.mesh.getBoundingInfo();
  63042. boundingInfo.isLocked = val;
  63043. },
  63044. enumerable: true,
  63045. configurable: true
  63046. });
  63047. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63048. /**
  63049. * Gets if `setParticles()` computes the particle rotations or not.
  63050. * Default value : true. The SPS is faster when it's set to false.
  63051. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63052. */
  63053. get: function () {
  63054. return this._computeParticleRotation;
  63055. },
  63056. /**
  63057. * Tells to `setParticles()` to compute the particle rotations or not.
  63058. * Default value : true. The SPS is faster when it's set to false.
  63059. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63060. */
  63061. set: function (val) {
  63062. this._computeParticleRotation = val;
  63063. },
  63064. enumerable: true,
  63065. configurable: true
  63066. });
  63067. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63068. /**
  63069. * Gets if `setParticles()` computes the particle colors or not.
  63070. * Default value : true. The SPS is faster when it's set to false.
  63071. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63072. */
  63073. get: function () {
  63074. return this._computeParticleColor;
  63075. },
  63076. /**
  63077. * Tells to `setParticles()` to compute the particle colors or not.
  63078. * Default value : true. The SPS is faster when it's set to false.
  63079. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63080. */
  63081. set: function (val) {
  63082. this._computeParticleColor = val;
  63083. },
  63084. enumerable: true,
  63085. configurable: true
  63086. });
  63087. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63088. /**
  63089. * Gets if `setParticles()` computes the particle textures or not.
  63090. * Default value : true. The SPS is faster when it's set to false.
  63091. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63092. */
  63093. get: function () {
  63094. return this._computeParticleTexture;
  63095. },
  63096. set: function (val) {
  63097. this._computeParticleTexture = val;
  63098. },
  63099. enumerable: true,
  63100. configurable: true
  63101. });
  63102. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63103. /**
  63104. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63105. * Default value : false. The SPS is faster when it's set to false.
  63106. * Note : the particle custom vertex positions aren't stored values.
  63107. */
  63108. get: function () {
  63109. return this._computeParticleVertex;
  63110. },
  63111. /**
  63112. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63113. * Default value : false. The SPS is faster when it's set to false.
  63114. * Note : the particle custom vertex positions aren't stored values.
  63115. */
  63116. set: function (val) {
  63117. this._computeParticleVertex = val;
  63118. },
  63119. enumerable: true,
  63120. configurable: true
  63121. });
  63122. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63123. /**
  63124. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63125. */
  63126. get: function () {
  63127. return this._computeBoundingBox;
  63128. },
  63129. /**
  63130. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63131. */
  63132. set: function (val) {
  63133. this._computeBoundingBox = val;
  63134. },
  63135. enumerable: true,
  63136. configurable: true
  63137. });
  63138. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63139. /**
  63140. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63141. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63142. * Default : `true`
  63143. */
  63144. get: function () {
  63145. return this._depthSortParticles;
  63146. },
  63147. /**
  63148. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  63149. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  63150. * Default : `true`
  63151. */
  63152. set: function (val) {
  63153. this._depthSortParticles = val;
  63154. },
  63155. enumerable: true,
  63156. configurable: true
  63157. });
  63158. // =======================================================================
  63159. // Particle behavior logic
  63160. // these following methods may be overwritten by the user to fit his needs
  63161. /**
  63162. * This function does nothing. It may be overwritten to set all the particle first values.
  63163. * The SPS doesn't call this function, you may have to call it by your own.
  63164. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63165. */
  63166. SolidParticleSystem.prototype.initParticles = function () {
  63167. };
  63168. /**
  63169. * This function does nothing. It may be overwritten to recycle a particle.
  63170. * The SPS doesn't call this function, you may have to call it by your own.
  63171. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63172. * @param particle The particle to recycle
  63173. * @returns the recycled particle
  63174. */
  63175. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  63176. return particle;
  63177. };
  63178. /**
  63179. * Updates a particle : this function should be overwritten by the user.
  63180. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  63181. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  63182. * @example : just set a particle position or velocity and recycle conditions
  63183. * @param particle The particle to update
  63184. * @returns the updated particle
  63185. */
  63186. SolidParticleSystem.prototype.updateParticle = function (particle) {
  63187. return particle;
  63188. };
  63189. /**
  63190. * Updates a vertex of a particle : it can be overwritten by the user.
  63191. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  63192. * @param particle the current particle
  63193. * @param vertex the current index of the current particle
  63194. * @param pt the index of the current vertex in the particle shape
  63195. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  63196. * @example : just set a vertex particle position
  63197. * @returns the updated vertex
  63198. */
  63199. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  63200. return vertex;
  63201. };
  63202. /**
  63203. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  63204. * This does nothing and may be overwritten by the user.
  63205. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63206. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63207. * @param update the boolean update value actually passed to setParticles()
  63208. */
  63209. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  63210. };
  63211. /**
  63212. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  63213. * This will be passed three parameters.
  63214. * This does nothing and may be overwritten by the user.
  63215. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63216. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  63217. * @param update the boolean update value actually passed to setParticles()
  63218. */
  63219. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  63220. };
  63221. return SolidParticleSystem;
  63222. }());
  63223. BABYLON.SolidParticleSystem = SolidParticleSystem;
  63224. })(BABYLON || (BABYLON = {}));
  63225. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  63226. var BABYLON;
  63227. (function (BABYLON) {
  63228. /**
  63229. * Class containing static functions to help procedurally build meshes
  63230. */
  63231. var MeshBuilder = /** @class */ (function () {
  63232. function MeshBuilder() {
  63233. }
  63234. MeshBuilder.updateSideOrientation = function (orientation) {
  63235. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  63236. return BABYLON.Mesh.DOUBLESIDE;
  63237. }
  63238. if (orientation === undefined || orientation === null) {
  63239. return BABYLON.Mesh.FRONTSIDE;
  63240. }
  63241. return orientation;
  63242. };
  63243. /**
  63244. * Creates a box mesh
  63245. * * The parameter `size` sets the size (float) of each box side (default 1)
  63246. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63247. * * 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)
  63248. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63249. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63250. * * 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
  63251. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63252. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63253. * @param name defines the name of the mesh
  63254. * @param options defines the options used to create the mesh
  63255. * @param scene defines the hosting scene
  63256. * @returns the box mesh
  63257. */
  63258. MeshBuilder.CreateBox = function (name, options, scene) {
  63259. if (scene === void 0) { scene = null; }
  63260. var box = new BABYLON.Mesh(name, scene);
  63261. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63262. box._originalBuilderSideOrientation = options.sideOrientation;
  63263. var vertexData = BABYLON.VertexData.CreateBox(options);
  63264. vertexData.applyToMesh(box, options.updatable);
  63265. return box;
  63266. };
  63267. /**
  63268. * Creates a sphere mesh
  63269. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63270. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  63271. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63272. * * 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
  63273. * * 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)
  63274. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63275. * * 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
  63276. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63277. * @param name defines the name of the mesh
  63278. * @param options defines the options used to create the mesh
  63279. * @param scene defines the hosting scene
  63280. * @returns the sphere mesh
  63281. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63282. */
  63283. MeshBuilder.CreateSphere = function (name, options, scene) {
  63284. var sphere = new BABYLON.Mesh(name, scene);
  63285. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63286. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63287. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63288. vertexData.applyToMesh(sphere, options.updatable);
  63289. return sphere;
  63290. };
  63291. /**
  63292. * Creates a plane polygonal mesh. By default, this is a disc
  63293. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63294. * * 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
  63295. * * 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
  63296. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63297. * * 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
  63298. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63299. * @param name defines the name of the mesh
  63300. * @param options defines the options used to create the mesh
  63301. * @param scene defines the hosting scene
  63302. * @returns the plane polygonal mesh
  63303. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63304. */
  63305. MeshBuilder.CreateDisc = function (name, options, scene) {
  63306. if (scene === void 0) { scene = null; }
  63307. var disc = new BABYLON.Mesh(name, scene);
  63308. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63309. disc._originalBuilderSideOrientation = options.sideOrientation;
  63310. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63311. vertexData.applyToMesh(disc, options.updatable);
  63312. return disc;
  63313. };
  63314. /**
  63315. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63316. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63317. * * 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`)
  63318. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63319. * * 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
  63320. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63321. * * 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
  63322. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63323. * @param name defines the name of the mesh
  63324. * @param options defines the options used to create the mesh
  63325. * @param scene defines the hosting scene
  63326. * @returns the icosahedron mesh
  63327. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63328. */
  63329. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63330. var sphere = new BABYLON.Mesh(name, scene);
  63331. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63332. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63333. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63334. vertexData.applyToMesh(sphere, options.updatable);
  63335. return sphere;
  63336. };
  63337. ;
  63338. /**
  63339. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63340. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63341. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63342. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63343. * * 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
  63344. * * 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
  63345. * * 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
  63346. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63347. * * 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
  63348. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63349. * * 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
  63350. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63351. * * 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
  63352. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63353. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63354. * @param name defines the name of the mesh
  63355. * @param options defines the options used to create the mesh
  63356. * @param scene defines the hosting scene
  63357. * @returns the ribbon mesh
  63358. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63359. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63360. */
  63361. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63362. if (scene === void 0) { scene = null; }
  63363. var pathArray = options.pathArray;
  63364. var closeArray = options.closeArray;
  63365. var closePath = options.closePath;
  63366. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63367. var instance = options.instance;
  63368. var updatable = options.updatable;
  63369. if (instance) { // existing ribbon instance update
  63370. // positionFunction : ribbon case
  63371. // only pathArray and sideOrientation parameters are taken into account for positions update
  63372. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63373. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63374. var positionFunction = function (positions) {
  63375. var minlg = pathArray[0].length;
  63376. var i = 0;
  63377. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63378. for (var si = 1; si <= ns; si++) {
  63379. for (var p = 0; p < pathArray.length; p++) {
  63380. var path = pathArray[p];
  63381. var l = path.length;
  63382. minlg = (minlg < l) ? minlg : l;
  63383. var j = 0;
  63384. while (j < minlg) {
  63385. positions[i] = path[j].x;
  63386. positions[i + 1] = path[j].y;
  63387. positions[i + 2] = path[j].z;
  63388. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63389. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63390. }
  63391. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63392. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63393. }
  63394. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63395. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63396. }
  63397. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63398. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63399. }
  63400. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63401. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63402. }
  63403. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63404. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63405. }
  63406. j++;
  63407. i += 3;
  63408. }
  63409. if (instance._closePath) {
  63410. positions[i] = path[0].x;
  63411. positions[i + 1] = path[0].y;
  63412. positions[i + 2] = path[0].z;
  63413. i += 3;
  63414. }
  63415. }
  63416. }
  63417. };
  63418. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63419. positionFunction(positions);
  63420. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63421. instance._boundingInfo.update(instance._worldMatrix);
  63422. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63423. if (options.colors) {
  63424. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63425. for (var c = 0; c < options.colors.length; c++) {
  63426. colors[c * 4] = options.colors[c].r;
  63427. colors[c * 4 + 1] = options.colors[c].g;
  63428. colors[c * 4 + 2] = options.colors[c].b;
  63429. colors[c * 4 + 3] = options.colors[c].a;
  63430. }
  63431. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63432. }
  63433. if (options.uvs) {
  63434. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63435. for (var i = 0; i < options.uvs.length; i++) {
  63436. uvs[i * 2] = options.uvs[i].x;
  63437. uvs[i * 2 + 1] = options.uvs[i].y;
  63438. }
  63439. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63440. }
  63441. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63442. var indices = instance.getIndices();
  63443. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63444. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63445. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63446. if (instance._closePath) {
  63447. var indexFirst = 0;
  63448. var indexLast = 0;
  63449. for (var p = 0; p < pathArray.length; p++) {
  63450. indexFirst = instance._idx[p] * 3;
  63451. if (p + 1 < pathArray.length) {
  63452. indexLast = (instance._idx[p + 1] - 1) * 3;
  63453. }
  63454. else {
  63455. indexLast = normals.length - 3;
  63456. }
  63457. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63458. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63459. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63460. normals[indexLast] = normals[indexFirst];
  63461. normals[indexLast + 1] = normals[indexFirst + 1];
  63462. normals[indexLast + 2] = normals[indexFirst + 2];
  63463. }
  63464. }
  63465. if (!(instance.areNormalsFrozen)) {
  63466. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63467. }
  63468. }
  63469. return instance;
  63470. }
  63471. else { // new ribbon creation
  63472. var ribbon = new BABYLON.Mesh(name, scene);
  63473. ribbon._originalBuilderSideOrientation = sideOrientation;
  63474. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63475. if (closePath) {
  63476. ribbon._idx = vertexData._idx;
  63477. }
  63478. ribbon._closePath = closePath;
  63479. ribbon._closeArray = closeArray;
  63480. vertexData.applyToMesh(ribbon, updatable);
  63481. return ribbon;
  63482. }
  63483. };
  63484. /**
  63485. * Creates a cylinder or a cone mesh
  63486. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63487. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63488. * * 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.
  63489. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63490. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63491. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63492. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63493. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63494. * * 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).
  63495. * * 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
  63496. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63497. * * 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
  63498. * * 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.
  63499. * * If `enclose` is false, a ring surface is one element.
  63500. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63501. * * 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
  63502. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63503. * * 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
  63504. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63505. * @param name defines the name of the mesh
  63506. * @param options defines the options used to create the mesh
  63507. * @param scene defines the hosting scene
  63508. * @returns the cylinder mesh
  63509. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63510. */
  63511. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63512. var cylinder = new BABYLON.Mesh(name, scene);
  63513. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63514. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63515. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63516. vertexData.applyToMesh(cylinder, options.updatable);
  63517. return cylinder;
  63518. };
  63519. /**
  63520. * Creates a torus mesh
  63521. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63522. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63523. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63524. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63525. * * 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
  63526. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63527. * @param name defines the name of the mesh
  63528. * @param options defines the options used to create the mesh
  63529. * @param scene defines the hosting scene
  63530. * @returns the torus mesh
  63531. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63532. */
  63533. MeshBuilder.CreateTorus = function (name, options, scene) {
  63534. var torus = new BABYLON.Mesh(name, scene);
  63535. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63536. torus._originalBuilderSideOrientation = options.sideOrientation;
  63537. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63538. vertexData.applyToMesh(torus, options.updatable);
  63539. return torus;
  63540. };
  63541. /**
  63542. * Creates a torus knot mesh
  63543. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63544. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63545. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63546. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63547. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63548. * * 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
  63549. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63550. * @param name defines the name of the mesh
  63551. * @param options defines the options used to create the mesh
  63552. * @param scene defines the hosting scene
  63553. * @returns the torus knot mesh
  63554. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63555. */
  63556. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63557. var torusKnot = new BABYLON.Mesh(name, scene);
  63558. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63559. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63560. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63561. vertexData.applyToMesh(torusKnot, options.updatable);
  63562. return torusKnot;
  63563. };
  63564. /**
  63565. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63566. * * 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
  63567. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63568. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63569. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63570. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63571. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63572. * * 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
  63573. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63574. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63575. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63576. * @param name defines the name of the new line system
  63577. * @param options defines the options used to create the line system
  63578. * @param scene defines the hosting scene
  63579. * @returns a new line system mesh
  63580. */
  63581. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63582. var instance = options.instance;
  63583. var lines = options.lines;
  63584. var colors = options.colors;
  63585. if (instance) { // lines update
  63586. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63587. var vertexColor;
  63588. var lineColors;
  63589. if (colors) {
  63590. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63591. }
  63592. var i = 0;
  63593. var c = 0;
  63594. for (var l = 0; l < lines.length; l++) {
  63595. var points = lines[l];
  63596. for (var p = 0; p < points.length; p++) {
  63597. positions[i] = points[p].x;
  63598. positions[i + 1] = points[p].y;
  63599. positions[i + 2] = points[p].z;
  63600. if (colors && vertexColor) {
  63601. lineColors = colors[l];
  63602. vertexColor[c] = lineColors[p].r;
  63603. vertexColor[c + 1] = lineColors[p].g;
  63604. vertexColor[c + 2] = lineColors[p].b;
  63605. vertexColor[c + 3] = lineColors[p].a;
  63606. c += 4;
  63607. }
  63608. i += 3;
  63609. }
  63610. }
  63611. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63612. if (colors && vertexColor) {
  63613. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63614. }
  63615. return instance;
  63616. }
  63617. // line system creation
  63618. var useVertexColor = (colors) ? true : false;
  63619. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63620. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63621. vertexData.applyToMesh(lineSystem, options.updatable);
  63622. return lineSystem;
  63623. };
  63624. /**
  63625. * Creates a line mesh
  63626. * 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
  63627. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63628. * * The parameter `points` is an array successive Vector3
  63629. * * 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
  63630. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63631. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63632. * * When updating an instance, remember that only point positions can change, not the number of points
  63633. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63634. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63635. * @param name defines the name of the new line system
  63636. * @param options defines the options used to create the line system
  63637. * @param scene defines the hosting scene
  63638. * @returns a new line mesh
  63639. */
  63640. MeshBuilder.CreateLines = function (name, options, scene) {
  63641. if (scene === void 0) { scene = null; }
  63642. var colors = (options.colors) ? [options.colors] : null;
  63643. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63644. return lines;
  63645. };
  63646. /**
  63647. * Creates a dashed line mesh
  63648. * * 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
  63649. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63650. * * The parameter `points` is an array successive Vector3
  63651. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63652. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63653. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63654. * * 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
  63655. * * When updating an instance, remember that only point positions can change, not the number of points
  63656. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63657. * @param name defines the name of the mesh
  63658. * @param options defines the options used to create the mesh
  63659. * @param scene defines the hosting scene
  63660. * @returns the dashed line mesh
  63661. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63662. */
  63663. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63664. if (scene === void 0) { scene = null; }
  63665. var points = options.points;
  63666. var instance = options.instance;
  63667. var gapSize = options.gapSize || 1;
  63668. var dashSize = options.dashSize || 3;
  63669. if (instance) { // dashed lines update
  63670. var positionFunction = function (positions) {
  63671. var curvect = BABYLON.Vector3.Zero();
  63672. var nbSeg = positions.length / 6;
  63673. var lg = 0;
  63674. var nb = 0;
  63675. var shft = 0;
  63676. var dashshft = 0;
  63677. var curshft = 0;
  63678. var p = 0;
  63679. var i = 0;
  63680. var j = 0;
  63681. for (i = 0; i < points.length - 1; i++) {
  63682. points[i + 1].subtractToRef(points[i], curvect);
  63683. lg += curvect.length();
  63684. }
  63685. shft = lg / nbSeg;
  63686. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63687. for (i = 0; i < points.length - 1; i++) {
  63688. points[i + 1].subtractToRef(points[i], curvect);
  63689. nb = Math.floor(curvect.length() / shft);
  63690. curvect.normalize();
  63691. j = 0;
  63692. while (j < nb && p < positions.length) {
  63693. curshft = shft * j;
  63694. positions[p] = points[i].x + curshft * curvect.x;
  63695. positions[p + 1] = points[i].y + curshft * curvect.y;
  63696. positions[p + 2] = points[i].z + curshft * curvect.z;
  63697. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63698. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63699. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63700. p += 6;
  63701. j++;
  63702. }
  63703. }
  63704. while (p < positions.length) {
  63705. positions[p] = points[i].x;
  63706. positions[p + 1] = points[i].y;
  63707. positions[p + 2] = points[i].z;
  63708. p += 3;
  63709. }
  63710. };
  63711. instance.updateMeshPositions(positionFunction, false);
  63712. return instance;
  63713. }
  63714. // dashed lines creation
  63715. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63716. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63717. vertexData.applyToMesh(dashedLines, options.updatable);
  63718. dashedLines.dashSize = dashSize;
  63719. dashedLines.gapSize = gapSize;
  63720. return dashedLines;
  63721. };
  63722. /**
  63723. * 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.
  63724. * * 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.
  63725. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63726. * * 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.
  63727. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63728. * * 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
  63729. * * 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
  63730. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63731. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63732. * * 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
  63733. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63734. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63735. * @param name defines the name of the mesh
  63736. * @param options defines the options used to create the mesh
  63737. * @param scene defines the hosting scene
  63738. * @returns the extruded shape mesh
  63739. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63740. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63741. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63742. */
  63743. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63744. if (scene === void 0) { scene = null; }
  63745. var path = options.path;
  63746. var shape = options.shape;
  63747. var scale = options.scale || 1;
  63748. var rotation = options.rotation || 0;
  63749. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63750. var updatable = options.updatable;
  63751. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63752. var instance = options.instance || null;
  63753. var invertUV = options.invertUV || false;
  63754. 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);
  63755. };
  63756. /**
  63757. * Creates an custom extruded shape mesh.
  63758. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63759. * * 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.
  63760. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63761. * * 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
  63762. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63763. * * 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
  63764. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63765. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63766. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63767. * * 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
  63768. * * 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
  63769. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63770. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63771. * * 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
  63772. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63773. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63774. * @param name defines the name of the mesh
  63775. * @param options defines the options used to create the mesh
  63776. * @param scene defines the hosting scene
  63777. * @returns the custom extruded shape mesh
  63778. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63779. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63780. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63781. */
  63782. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63783. var path = options.path;
  63784. var shape = options.shape;
  63785. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63786. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63787. var ribbonCloseArray = options.ribbonCloseArray || false;
  63788. var ribbonClosePath = options.ribbonClosePath || false;
  63789. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63790. var updatable = options.updatable;
  63791. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63792. var instance = options.instance;
  63793. var invertUV = options.invertUV || false;
  63794. 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);
  63795. };
  63796. /**
  63797. * Creates lathe mesh.
  63798. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63799. * * 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
  63800. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63801. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63802. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63803. * * 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
  63804. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63805. * * 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
  63806. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63807. * * 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
  63808. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63809. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63810. * @param name defines the name of the mesh
  63811. * @param options defines the options used to create the mesh
  63812. * @param scene defines the hosting scene
  63813. * @returns the lathe mesh
  63814. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63815. */
  63816. MeshBuilder.CreateLathe = function (name, options, scene) {
  63817. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63818. var closed = (options.closed === undefined) ? true : options.closed;
  63819. var shape = options.shape;
  63820. var radius = options.radius || 1;
  63821. var tessellation = options.tessellation || 64;
  63822. var clip = options.clip || 0;
  63823. var updatable = options.updatable;
  63824. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63825. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63826. var pi2 = Math.PI * 2;
  63827. var paths = new Array();
  63828. var invertUV = options.invertUV || false;
  63829. var i = 0;
  63830. var p = 0;
  63831. var step = pi2 / tessellation * arc;
  63832. var rotated;
  63833. var path = new Array();
  63834. for (i = 0; i <= tessellation - clip; i++) {
  63835. var path = [];
  63836. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63837. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63838. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63839. }
  63840. for (p = 0; p < shape.length; p++) {
  63841. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63842. path.push(rotated);
  63843. }
  63844. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63845. 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));
  63846. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63847. }
  63848. paths.push(path);
  63849. }
  63850. // lathe ribbon
  63851. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63852. return lathe;
  63853. };
  63854. /**
  63855. * Creates a plane mesh
  63856. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63857. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63858. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63859. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63860. * * 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
  63861. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63862. * @param name defines the name of the mesh
  63863. * @param options defines the options used to create the mesh
  63864. * @param scene defines the hosting scene
  63865. * @returns the plane mesh
  63866. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63867. */
  63868. MeshBuilder.CreatePlane = function (name, options, scene) {
  63869. var plane = new BABYLON.Mesh(name, scene);
  63870. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63871. plane._originalBuilderSideOrientation = options.sideOrientation;
  63872. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63873. vertexData.applyToMesh(plane, options.updatable);
  63874. if (options.sourcePlane) {
  63875. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63876. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63877. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63878. plane.rotate(vectorProduct, product);
  63879. }
  63880. return plane;
  63881. };
  63882. /**
  63883. * Creates a ground mesh
  63884. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63885. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63886. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63887. * @param name defines the name of the mesh
  63888. * @param options defines the options used to create the mesh
  63889. * @param scene defines the hosting scene
  63890. * @returns the ground mesh
  63891. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63892. */
  63893. MeshBuilder.CreateGround = function (name, options, scene) {
  63894. var ground = new BABYLON.GroundMesh(name, scene);
  63895. ground._setReady(false);
  63896. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63897. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63898. ground._width = options.width || 1;
  63899. ground._height = options.height || 1;
  63900. ground._maxX = ground._width / 2;
  63901. ground._maxZ = ground._height / 2;
  63902. ground._minX = -ground._maxX;
  63903. ground._minZ = -ground._maxZ;
  63904. var vertexData = BABYLON.VertexData.CreateGround(options);
  63905. vertexData.applyToMesh(ground, options.updatable);
  63906. ground._setReady(true);
  63907. return ground;
  63908. };
  63909. /**
  63910. * Creates a tiled ground mesh
  63911. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63912. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63913. * * 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
  63914. * * 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
  63915. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63916. * @param name defines the name of the mesh
  63917. * @param options defines the options used to create the mesh
  63918. * @param scene defines the hosting scene
  63919. * @returns the tiled ground mesh
  63920. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63921. */
  63922. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63923. var tiledGround = new BABYLON.Mesh(name, scene);
  63924. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63925. vertexData.applyToMesh(tiledGround, options.updatable);
  63926. return tiledGround;
  63927. };
  63928. /**
  63929. * Creates a ground mesh from a height map
  63930. * * The parameter `url` sets the URL of the height map image resource.
  63931. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63932. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63933. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63934. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63935. * * 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.
  63936. * * 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).
  63937. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63938. * @param name defines the name of the mesh
  63939. * @param url defines the url to the height map
  63940. * @param options defines the options used to create the mesh
  63941. * @param scene defines the hosting scene
  63942. * @returns the ground mesh
  63943. * @see http://doc.babylonjs.com/babylon101/height_map
  63944. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63945. */
  63946. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63947. var width = options.width || 10.0;
  63948. var height = options.height || 10.0;
  63949. var subdivisions = options.subdivisions || 1 | 0;
  63950. var minHeight = options.minHeight || 0.0;
  63951. var maxHeight = options.maxHeight || 1.0;
  63952. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63953. var updatable = options.updatable;
  63954. var onReady = options.onReady;
  63955. var ground = new BABYLON.GroundMesh(name, scene);
  63956. ground._subdivisionsX = subdivisions;
  63957. ground._subdivisionsY = subdivisions;
  63958. ground._width = width;
  63959. ground._height = height;
  63960. ground._maxX = ground._width / 2.0;
  63961. ground._maxZ = ground._height / 2.0;
  63962. ground._minX = -ground._maxX;
  63963. ground._minZ = -ground._maxZ;
  63964. ground._setReady(false);
  63965. var onload = function (img) {
  63966. // Getting height map data
  63967. var canvas = document.createElement("canvas");
  63968. var context = canvas.getContext("2d");
  63969. if (!context) {
  63970. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63971. }
  63972. if (scene.isDisposed) {
  63973. return;
  63974. }
  63975. var bufferWidth = img.width;
  63976. var bufferHeight = img.height;
  63977. canvas.width = bufferWidth;
  63978. canvas.height = bufferHeight;
  63979. context.drawImage(img, 0, 0);
  63980. // Create VertexData from map data
  63981. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63982. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63983. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63984. width: width, height: height,
  63985. subdivisions: subdivisions,
  63986. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63987. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63988. });
  63989. vertexData.applyToMesh(ground, updatable);
  63990. //execute ready callback, if set
  63991. if (onReady) {
  63992. onReady(ground);
  63993. }
  63994. ground._setReady(true);
  63995. };
  63996. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63997. return ground;
  63998. };
  63999. /**
  64000. * Creates a polygon mesh
  64001. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64002. * * 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
  64003. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64004. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64005. * * 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)
  64006. * * Remember you can only change the shape positions, not their number when updating a polygon
  64007. * @param name defines the name of the mesh
  64008. * @param options defines the options used to create the mesh
  64009. * @param scene defines the hosting scene
  64010. * @returns the polygon mesh
  64011. */
  64012. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64013. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64014. var shape = options.shape;
  64015. var holes = options.holes || [];
  64016. var depth = options.depth || 0;
  64017. var contours = [];
  64018. var hole = [];
  64019. for (var i = 0; i < shape.length; i++) {
  64020. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64021. }
  64022. var epsilon = 0.00000001;
  64023. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64024. contours.pop();
  64025. }
  64026. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64027. for (var hNb = 0; hNb < holes.length; hNb++) {
  64028. hole = [];
  64029. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64030. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64031. }
  64032. polygonTriangulation.addHole(hole);
  64033. }
  64034. var polygon = polygonTriangulation.build(options.updatable, depth);
  64035. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64036. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64037. vertexData.applyToMesh(polygon, options.updatable);
  64038. return polygon;
  64039. };
  64040. ;
  64041. /**
  64042. * Creates an extruded polygon mesh, with depth in the Y direction.
  64043. * * 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)
  64044. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64045. * @param name defines the name of the mesh
  64046. * @param options defines the options used to create the mesh
  64047. * @param scene defines the hosting scene
  64048. * @returns the polygon mesh
  64049. */
  64050. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64051. return MeshBuilder.CreatePolygon(name, options, scene);
  64052. };
  64053. ;
  64054. /**
  64055. * Creates a tube mesh.
  64056. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64057. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64058. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64059. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64060. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64061. * * 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)
  64062. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64063. * * 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
  64064. * * 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
  64065. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64066. * * 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
  64067. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64068. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64069. * @param name defines the name of the mesh
  64070. * @param options defines the options used to create the mesh
  64071. * @param scene defines the hosting scene
  64072. * @returns the tube mesh
  64073. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64074. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64075. */
  64076. MeshBuilder.CreateTube = function (name, options, scene) {
  64077. var path = options.path;
  64078. var instance = options.instance;
  64079. var radius = 1.0;
  64080. if (instance) {
  64081. radius = instance.radius;
  64082. }
  64083. if (options.radius !== undefined) {
  64084. radius = options.radius;
  64085. }
  64086. ;
  64087. var tessellation = options.tessellation || 64 | 0;
  64088. var radiusFunction = options.radiusFunction || null;
  64089. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64090. var invertUV = options.invertUV || false;
  64091. var updatable = options.updatable;
  64092. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64093. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64094. // tube geometry
  64095. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64096. var tangents = path3D.getTangents();
  64097. var normals = path3D.getNormals();
  64098. var distances = path3D.getDistances();
  64099. var pi2 = Math.PI * 2;
  64100. var step = pi2 / tessellation * arc;
  64101. var returnRadius = function () { return radius; };
  64102. var radiusFunctionFinal = radiusFunction || returnRadius;
  64103. var circlePath;
  64104. var rad;
  64105. var normal;
  64106. var rotated;
  64107. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64108. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64109. for (var i = 0; i < path.length; i++) {
  64110. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64111. circlePath = Array(); // current circle array
  64112. normal = normals[i]; // current normal
  64113. for (var t = 0; t < tessellation; t++) {
  64114. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64115. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64116. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64117. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64118. circlePath[t] = rotated;
  64119. }
  64120. circlePaths[index] = circlePath;
  64121. index++;
  64122. }
  64123. // cap
  64124. var capPath = function (nbPoints, pathIndex) {
  64125. var pointCap = Array();
  64126. for (var i = 0; i < nbPoints; i++) {
  64127. pointCap.push(path[pathIndex]);
  64128. }
  64129. return pointCap;
  64130. };
  64131. switch (cap) {
  64132. case BABYLON.Mesh.NO_CAP:
  64133. break;
  64134. case BABYLON.Mesh.CAP_START:
  64135. circlePaths[0] = capPath(tessellation, 0);
  64136. circlePaths[1] = circlePaths[2].slice(0);
  64137. break;
  64138. case BABYLON.Mesh.CAP_END:
  64139. circlePaths[index] = circlePaths[index - 1].slice(0);
  64140. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64141. break;
  64142. case BABYLON.Mesh.CAP_ALL:
  64143. circlePaths[0] = capPath(tessellation, 0);
  64144. circlePaths[1] = circlePaths[2].slice(0);
  64145. circlePaths[index] = circlePaths[index - 1].slice(0);
  64146. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64147. break;
  64148. default:
  64149. break;
  64150. }
  64151. return circlePaths;
  64152. };
  64153. var path3D;
  64154. var pathArray;
  64155. if (instance) { // tube update
  64156. var arc = options.arc || instance.arc;
  64157. path3D = (instance.path3D).update(path);
  64158. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  64159. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  64160. instance.path3D = path3D;
  64161. instance.pathArray = pathArray;
  64162. instance.arc = arc;
  64163. instance.radius = radius;
  64164. return instance;
  64165. }
  64166. // tube creation
  64167. path3D = new BABYLON.Path3D(path);
  64168. var newPathArray = new Array();
  64169. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64170. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  64171. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64172. tube.pathArray = pathArray;
  64173. tube.path3D = path3D;
  64174. tube.tessellation = tessellation;
  64175. tube.cap = cap;
  64176. tube.arc = options.arc;
  64177. tube.radius = radius;
  64178. return tube;
  64179. };
  64180. /**
  64181. * Creates a polyhedron mesh
  64182. * * 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
  64183. * * The parameter `size` (positive float, default 1) sets the polygon size
  64184. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  64185. * * 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`
  64186. * * 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
  64187. * * 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)`)
  64188. * * 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
  64189. * * 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
  64190. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64191. * * 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
  64192. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64193. * @param name defines the name of the mesh
  64194. * @param options defines the options used to create the mesh
  64195. * @param scene defines the hosting scene
  64196. * @returns the polyhedron mesh
  64197. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  64198. */
  64199. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  64200. var polyhedron = new BABYLON.Mesh(name, scene);
  64201. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64202. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  64203. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  64204. vertexData.applyToMesh(polyhedron, options.updatable);
  64205. return polyhedron;
  64206. };
  64207. /**
  64208. * Creates a decal mesh.
  64209. * 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
  64210. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  64211. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  64212. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  64213. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  64214. * @param name defines the name of the mesh
  64215. * @param sourceMesh defines the mesh where the decal must be applied
  64216. * @param options defines the options used to create the mesh
  64217. * @param scene defines the hosting scene
  64218. * @returns the decal mesh
  64219. * @see http://doc.babylonjs.com/how_to/decals
  64220. */
  64221. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  64222. var indices = sourceMesh.getIndices();
  64223. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64224. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64225. var position = options.position || BABYLON.Vector3.Zero();
  64226. var normal = options.normal || BABYLON.Vector3.Up();
  64227. var size = options.size || BABYLON.Vector3.One();
  64228. var angle = options.angle || 0;
  64229. // Getting correct rotation
  64230. if (!normal) {
  64231. var target = new BABYLON.Vector3(0, 0, 1);
  64232. var camera = sourceMesh.getScene().activeCamera;
  64233. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  64234. normal = camera.globalPosition.subtract(cameraWorldTarget);
  64235. }
  64236. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  64237. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  64238. var pitch = Math.atan2(normal.y, len);
  64239. // Matrix
  64240. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  64241. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  64242. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  64243. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64244. var vertexData = new BABYLON.VertexData();
  64245. vertexData.indices = [];
  64246. vertexData.positions = [];
  64247. vertexData.normals = [];
  64248. vertexData.uvs = [];
  64249. var currentVertexDataIndex = 0;
  64250. var extractDecalVector3 = function (indexId) {
  64251. var result = new BABYLON.PositionNormalVertex();
  64252. if (!indices || !positions || !normals) {
  64253. return result;
  64254. }
  64255. var vertexId = indices[indexId];
  64256. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64257. // Send vector to decal local world
  64258. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64259. // Get normal
  64260. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64261. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64262. return result;
  64263. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64264. var clip = function (vertices, axis) {
  64265. if (vertices.length === 0) {
  64266. return vertices;
  64267. }
  64268. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64269. var clipVertices = function (v0, v1) {
  64270. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64271. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64272. };
  64273. var result = new Array();
  64274. for (var index = 0; index < vertices.length; index += 3) {
  64275. var v1Out;
  64276. var v2Out;
  64277. var v3Out;
  64278. var total = 0;
  64279. var nV1 = null;
  64280. var nV2 = null;
  64281. var nV3 = null;
  64282. var nV4 = null;
  64283. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64284. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64285. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64286. v1Out = d1 > 0;
  64287. v2Out = d2 > 0;
  64288. v3Out = d3 > 0;
  64289. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64290. switch (total) {
  64291. case 0:
  64292. result.push(vertices[index]);
  64293. result.push(vertices[index + 1]);
  64294. result.push(vertices[index + 2]);
  64295. break;
  64296. case 1:
  64297. if (v1Out) {
  64298. nV1 = vertices[index + 1];
  64299. nV2 = vertices[index + 2];
  64300. nV3 = clipVertices(vertices[index], nV1);
  64301. nV4 = clipVertices(vertices[index], nV2);
  64302. }
  64303. if (v2Out) {
  64304. nV1 = vertices[index];
  64305. nV2 = vertices[index + 2];
  64306. nV3 = clipVertices(vertices[index + 1], nV1);
  64307. nV4 = clipVertices(vertices[index + 1], nV2);
  64308. result.push(nV3);
  64309. result.push(nV2.clone());
  64310. result.push(nV1.clone());
  64311. result.push(nV2.clone());
  64312. result.push(nV3.clone());
  64313. result.push(nV4);
  64314. break;
  64315. }
  64316. if (v3Out) {
  64317. nV1 = vertices[index];
  64318. nV2 = vertices[index + 1];
  64319. nV3 = clipVertices(vertices[index + 2], nV1);
  64320. nV4 = clipVertices(vertices[index + 2], nV2);
  64321. }
  64322. if (nV1 && nV2 && nV3 && nV4) {
  64323. result.push(nV1.clone());
  64324. result.push(nV2.clone());
  64325. result.push(nV3);
  64326. result.push(nV4);
  64327. result.push(nV3.clone());
  64328. result.push(nV2.clone());
  64329. }
  64330. break;
  64331. case 2:
  64332. if (!v1Out) {
  64333. nV1 = vertices[index].clone();
  64334. nV2 = clipVertices(nV1, vertices[index + 1]);
  64335. nV3 = clipVertices(nV1, vertices[index + 2]);
  64336. result.push(nV1);
  64337. result.push(nV2);
  64338. result.push(nV3);
  64339. }
  64340. if (!v2Out) {
  64341. nV1 = vertices[index + 1].clone();
  64342. nV2 = clipVertices(nV1, vertices[index + 2]);
  64343. nV3 = clipVertices(nV1, vertices[index]);
  64344. result.push(nV1);
  64345. result.push(nV2);
  64346. result.push(nV3);
  64347. }
  64348. if (!v3Out) {
  64349. nV1 = vertices[index + 2].clone();
  64350. nV2 = clipVertices(nV1, vertices[index]);
  64351. nV3 = clipVertices(nV1, vertices[index + 1]);
  64352. result.push(nV1);
  64353. result.push(nV2);
  64354. result.push(nV3);
  64355. }
  64356. break;
  64357. case 3:
  64358. break;
  64359. }
  64360. }
  64361. return result;
  64362. };
  64363. for (var index = 0; index < indices.length; index += 3) {
  64364. var faceVertices = new Array();
  64365. faceVertices.push(extractDecalVector3(index));
  64366. faceVertices.push(extractDecalVector3(index + 1));
  64367. faceVertices.push(extractDecalVector3(index + 2));
  64368. // Clip
  64369. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64370. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64371. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64372. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64373. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64374. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64375. if (faceVertices.length === 0) {
  64376. continue;
  64377. }
  64378. // Add UVs and get back to world
  64379. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64380. var vertex = faceVertices[vIndex];
  64381. //TODO check for Int32Array | Uint32Array | Uint16Array
  64382. vertexData.indices.push(currentVertexDataIndex);
  64383. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64384. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64385. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64386. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64387. currentVertexDataIndex++;
  64388. }
  64389. }
  64390. // Return mesh
  64391. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64392. vertexData.applyToMesh(decal);
  64393. decal.position = position.clone();
  64394. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64395. return decal;
  64396. };
  64397. // Privates
  64398. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64399. // extrusion geometry
  64400. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64401. var tangents = path3D.getTangents();
  64402. var normals = path3D.getNormals();
  64403. var binormals = path3D.getBinormals();
  64404. var distances = path3D.getDistances();
  64405. var angle = 0;
  64406. var returnScale = function () { return scale !== null ? scale : 1; };
  64407. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64408. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64409. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64410. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64411. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64412. for (var i = 0; i < curve.length; i++) {
  64413. var shapePath = new Array();
  64414. var angleStep = rotate(i, distances[i]);
  64415. var scaleRatio = scl(i, distances[i]);
  64416. for (var p = 0; p < shape.length; p++) {
  64417. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64418. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64419. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64420. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64421. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64422. shapePath[p] = rotated;
  64423. }
  64424. shapePaths[index] = shapePath;
  64425. angle += angleStep;
  64426. index++;
  64427. }
  64428. // cap
  64429. var capPath = function (shapePath) {
  64430. var pointCap = Array();
  64431. var barycenter = BABYLON.Vector3.Zero();
  64432. var i;
  64433. for (i = 0; i < shapePath.length; i++) {
  64434. barycenter.addInPlace(shapePath[i]);
  64435. }
  64436. barycenter.scaleInPlace(1.0 / shapePath.length);
  64437. for (i = 0; i < shapePath.length; i++) {
  64438. pointCap.push(barycenter);
  64439. }
  64440. return pointCap;
  64441. };
  64442. switch (cap) {
  64443. case BABYLON.Mesh.NO_CAP:
  64444. break;
  64445. case BABYLON.Mesh.CAP_START:
  64446. shapePaths[0] = capPath(shapePaths[2]);
  64447. shapePaths[1] = shapePaths[2];
  64448. break;
  64449. case BABYLON.Mesh.CAP_END:
  64450. shapePaths[index] = shapePaths[index - 1];
  64451. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64452. break;
  64453. case BABYLON.Mesh.CAP_ALL:
  64454. shapePaths[0] = capPath(shapePaths[2]);
  64455. shapePaths[1] = shapePaths[2];
  64456. shapePaths[index] = shapePaths[index - 1];
  64457. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64458. break;
  64459. default:
  64460. break;
  64461. }
  64462. return shapePaths;
  64463. };
  64464. var path3D;
  64465. var pathArray;
  64466. if (instance) { // instance update
  64467. path3D = (instance.path3D).update(curve);
  64468. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64469. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64470. return instance;
  64471. }
  64472. // extruded shape creation
  64473. path3D = new BABYLON.Path3D(curve);
  64474. var newShapePaths = new Array();
  64475. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64476. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64477. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64478. extrudedGeneric.pathArray = pathArray;
  64479. extrudedGeneric.path3D = path3D;
  64480. extrudedGeneric.cap = cap;
  64481. return extrudedGeneric;
  64482. };
  64483. return MeshBuilder;
  64484. }());
  64485. BABYLON.MeshBuilder = MeshBuilder;
  64486. })(BABYLON || (BABYLON = {}));
  64487. //# sourceMappingURL=babylon.meshBuilder.js.map
  64488. var BABYLON;
  64489. (function (BABYLON) {
  64490. /**
  64491. * Draco compression (https://google.github.io/draco/)
  64492. *
  64493. * This class wraps the Draco module.
  64494. *
  64495. * **Encoder**
  64496. *
  64497. * The encoder is not currently implemented.
  64498. *
  64499. * **Decoder**
  64500. *
  64501. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64502. *
  64503. * To update the configuration, use the following code:
  64504. * ```javascript
  64505. * BABYLON.DracoCompression.Configuration = {
  64506. * decoder: {
  64507. * wasmUrl: "<url to the WebAssembly library>",
  64508. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64509. * fallbackUrl: "<url to the fallback JavaScript library>",
  64510. * }
  64511. * };
  64512. * ```
  64513. *
  64514. * 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.
  64515. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64516. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64517. *
  64518. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64519. * ```javascript
  64520. * var dracoCompression = new BABYLON.DracoCompression();
  64521. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64522. * [BABYLON.VertexBuffer.PositionKind]: 0
  64523. * });
  64524. * ```
  64525. *
  64526. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64527. */
  64528. var DracoCompression = /** @class */ (function () {
  64529. /**
  64530. * Constructor
  64531. */
  64532. function DracoCompression() {
  64533. }
  64534. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64535. /**
  64536. * Returns true if the decoder is available.
  64537. */
  64538. get: function () {
  64539. if (typeof DracoDecoderModule !== "undefined") {
  64540. return true;
  64541. }
  64542. var decoder = DracoCompression.Configuration.decoder;
  64543. if (decoder) {
  64544. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64545. return true;
  64546. }
  64547. if (decoder.fallbackUrl) {
  64548. return true;
  64549. }
  64550. }
  64551. return false;
  64552. },
  64553. enumerable: true,
  64554. configurable: true
  64555. });
  64556. /**
  64557. * Stop all async operations and release resources.
  64558. */
  64559. DracoCompression.prototype.dispose = function () {
  64560. };
  64561. /**
  64562. * Decode Draco compressed mesh data to vertex data.
  64563. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64564. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64565. * @returns A promise that resolves with the decoded vertex data
  64566. */
  64567. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64568. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64569. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64570. var module = wrappedModule.module;
  64571. var vertexData = new BABYLON.VertexData();
  64572. var buffer = new module.DecoderBuffer();
  64573. buffer.Init(dataView, dataView.byteLength);
  64574. var decoder = new module.Decoder();
  64575. var geometry;
  64576. var status;
  64577. try {
  64578. var type = decoder.GetEncodedGeometryType(buffer);
  64579. switch (type) {
  64580. case module.TRIANGULAR_MESH:
  64581. geometry = new module.Mesh();
  64582. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64583. break;
  64584. case module.POINT_CLOUD:
  64585. geometry = new module.PointCloud();
  64586. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64587. break;
  64588. default:
  64589. throw new Error("Invalid geometry type " + type);
  64590. }
  64591. if (!status.ok() || !geometry.ptr) {
  64592. throw new Error(status.error_msg());
  64593. }
  64594. var numPoints = geometry.num_points();
  64595. if (type === module.TRIANGULAR_MESH) {
  64596. var numFaces = geometry.num_faces();
  64597. var faceIndices = new module.DracoInt32Array();
  64598. try {
  64599. var indices = new Uint32Array(numFaces * 3);
  64600. for (var i = 0; i < numFaces; i++) {
  64601. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64602. var offset = i * 3;
  64603. indices[offset + 0] = faceIndices.GetValue(0);
  64604. indices[offset + 1] = faceIndices.GetValue(1);
  64605. indices[offset + 2] = faceIndices.GetValue(2);
  64606. }
  64607. vertexData.indices = indices;
  64608. }
  64609. finally {
  64610. module.destroy(faceIndices);
  64611. }
  64612. }
  64613. for (var kind in attributes) {
  64614. var uniqueId = attributes[kind];
  64615. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64616. var dracoData = new module.DracoFloat32Array();
  64617. try {
  64618. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64619. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64620. for (var i = 0; i < babylonData.length; i++) {
  64621. babylonData[i] = dracoData.GetValue(i);
  64622. }
  64623. vertexData.set(babylonData, kind);
  64624. }
  64625. finally {
  64626. module.destroy(dracoData);
  64627. }
  64628. }
  64629. }
  64630. finally {
  64631. if (geometry) {
  64632. module.destroy(geometry);
  64633. }
  64634. module.destroy(decoder);
  64635. module.destroy(buffer);
  64636. }
  64637. return vertexData;
  64638. });
  64639. };
  64640. DracoCompression._GetDecoderModule = function () {
  64641. if (!DracoCompression._DecoderModulePromise) {
  64642. var promise = null;
  64643. var config_1 = {};
  64644. if (typeof DracoDecoderModule !== "undefined") {
  64645. promise = Promise.resolve();
  64646. }
  64647. else {
  64648. var decoder = DracoCompression.Configuration.decoder;
  64649. if (decoder) {
  64650. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64651. promise = Promise.all([
  64652. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64653. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64654. config_1.wasmBinary = data;
  64655. })
  64656. ]);
  64657. }
  64658. else if (decoder.fallbackUrl) {
  64659. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64660. }
  64661. }
  64662. }
  64663. if (!promise) {
  64664. throw new Error("Draco decoder module is not available");
  64665. }
  64666. DracoCompression._DecoderModulePromise = promise.then(function () {
  64667. return new Promise(function (resolve) {
  64668. config_1.onModuleLoaded = function (decoderModule) {
  64669. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64670. resolve({ module: decoderModule });
  64671. };
  64672. DracoDecoderModule(config_1);
  64673. });
  64674. });
  64675. }
  64676. return DracoCompression._DecoderModulePromise;
  64677. };
  64678. DracoCompression._LoadScriptAsync = function (url) {
  64679. return new Promise(function (resolve, reject) {
  64680. BABYLON.Tools.LoadScript(url, function () {
  64681. resolve();
  64682. }, function (message) {
  64683. reject(new Error(message));
  64684. });
  64685. });
  64686. };
  64687. DracoCompression._LoadFileAsync = function (url) {
  64688. return new Promise(function (resolve, reject) {
  64689. BABYLON.Tools.LoadFile(url, function (data) {
  64690. resolve(data);
  64691. }, undefined, undefined, true, function (request, exception) {
  64692. reject(exception);
  64693. });
  64694. });
  64695. };
  64696. /**
  64697. * The configuration. Defaults to the following urls:
  64698. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64699. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64700. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64701. */
  64702. DracoCompression.Configuration = {
  64703. decoder: {
  64704. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64705. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64706. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64707. }
  64708. };
  64709. return DracoCompression;
  64710. }());
  64711. BABYLON.DracoCompression = DracoCompression;
  64712. })(BABYLON || (BABYLON = {}));
  64713. //# sourceMappingURL=babylon.dracoCompression.js.map
  64714. var BABYLON;
  64715. (function (BABYLON) {
  64716. var AudioEngine = /** @class */ (function () {
  64717. function AudioEngine() {
  64718. this._audioContext = null;
  64719. this._audioContextInitialized = false;
  64720. this.canUseWebAudio = false;
  64721. this.WarnedWebAudioUnsupported = false;
  64722. this.unlocked = false;
  64723. this.isMP3supported = false;
  64724. this.isOGGsupported = false;
  64725. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64726. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64727. this.canUseWebAudio = true;
  64728. }
  64729. var audioElem = document.createElement('audio');
  64730. try {
  64731. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64732. this.isMP3supported = true;
  64733. }
  64734. }
  64735. catch (e) {
  64736. // protect error during capability check.
  64737. }
  64738. try {
  64739. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64740. this.isOGGsupported = true;
  64741. }
  64742. }
  64743. catch (e) {
  64744. // protect error during capability check.
  64745. }
  64746. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64747. this._unlockiOSaudio();
  64748. }
  64749. else {
  64750. this.unlocked = true;
  64751. }
  64752. }
  64753. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64754. get: function () {
  64755. if (!this._audioContextInitialized) {
  64756. this._initializeAudioContext();
  64757. }
  64758. return this._audioContext;
  64759. },
  64760. enumerable: true,
  64761. configurable: true
  64762. });
  64763. AudioEngine.prototype._unlockiOSaudio = function () {
  64764. var _this = this;
  64765. var unlockaudio = function () {
  64766. if (!_this.audioContext) {
  64767. return;
  64768. }
  64769. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64770. var source = _this.audioContext.createBufferSource();
  64771. source.buffer = buffer;
  64772. source.connect(_this.audioContext.destination);
  64773. source.start(0);
  64774. setTimeout(function () {
  64775. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64776. _this.unlocked = true;
  64777. window.removeEventListener('touchend', unlockaudio, false);
  64778. if (_this.onAudioUnlocked) {
  64779. _this.onAudioUnlocked();
  64780. }
  64781. }
  64782. }, 0);
  64783. };
  64784. window.addEventListener('touchend', unlockaudio, false);
  64785. };
  64786. AudioEngine.prototype._initializeAudioContext = function () {
  64787. try {
  64788. if (this.canUseWebAudio) {
  64789. this._audioContext = new AudioContext();
  64790. // create a global volume gain node
  64791. this.masterGain = this._audioContext.createGain();
  64792. this.masterGain.gain.value = 1;
  64793. this.masterGain.connect(this._audioContext.destination);
  64794. this._audioContextInitialized = true;
  64795. }
  64796. }
  64797. catch (e) {
  64798. this.canUseWebAudio = false;
  64799. BABYLON.Tools.Error("Web Audio: " + e.message);
  64800. }
  64801. };
  64802. AudioEngine.prototype.dispose = function () {
  64803. if (this.canUseWebAudio && this._audioContextInitialized) {
  64804. if (this._connectedAnalyser && this._audioContext) {
  64805. this._connectedAnalyser.stopDebugCanvas();
  64806. this._connectedAnalyser.dispose();
  64807. this.masterGain.disconnect();
  64808. this.masterGain.connect(this._audioContext.destination);
  64809. this._connectedAnalyser = null;
  64810. }
  64811. this.masterGain.gain.value = 1;
  64812. }
  64813. this.WarnedWebAudioUnsupported = false;
  64814. };
  64815. AudioEngine.prototype.getGlobalVolume = function () {
  64816. if (this.canUseWebAudio && this._audioContextInitialized) {
  64817. return this.masterGain.gain.value;
  64818. }
  64819. else {
  64820. return -1;
  64821. }
  64822. };
  64823. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64824. if (this.canUseWebAudio && this._audioContextInitialized) {
  64825. this.masterGain.gain.value = newVolume;
  64826. }
  64827. };
  64828. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64829. if (this._connectedAnalyser) {
  64830. this._connectedAnalyser.stopDebugCanvas();
  64831. }
  64832. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64833. this._connectedAnalyser = analyser;
  64834. this.masterGain.disconnect();
  64835. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64836. }
  64837. };
  64838. return AudioEngine;
  64839. }());
  64840. BABYLON.AudioEngine = AudioEngine;
  64841. })(BABYLON || (BABYLON = {}));
  64842. //# sourceMappingURL=babylon.audioEngine.js.map
  64843. var BABYLON;
  64844. (function (BABYLON) {
  64845. var Sound = /** @class */ (function () {
  64846. /**
  64847. * Create a sound and attach it to a scene
  64848. * @param name Name of your sound
  64849. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64850. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64851. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64852. */
  64853. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64854. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64855. var _this = this;
  64856. this.autoplay = false;
  64857. this.loop = false;
  64858. this.useCustomAttenuation = false;
  64859. this.spatialSound = false;
  64860. this.refDistance = 1;
  64861. this.rolloffFactor = 1;
  64862. this.maxDistance = 100;
  64863. this.distanceModel = "linear";
  64864. this._panningModel = "equalpower";
  64865. /**
  64866. * Observable event when the current playing sound finishes.
  64867. */
  64868. this.onEndedObservable = new BABYLON.Observable();
  64869. this._playbackRate = 1;
  64870. this._streaming = false;
  64871. this._startTime = 0;
  64872. this._startOffset = 0;
  64873. this._position = BABYLON.Vector3.Zero();
  64874. /** @hidden */
  64875. this._positionInEmitterSpace = false;
  64876. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64877. this._volume = 1;
  64878. this._isReadyToPlay = false;
  64879. this.isPlaying = false;
  64880. this.isPaused = false;
  64881. this._isDirectional = false;
  64882. // Used if you'd like to create a directional sound.
  64883. // If not set, the sound will be omnidirectional
  64884. this._coneInnerAngle = 360;
  64885. this._coneOuterAngle = 360;
  64886. this._coneOuterGain = 0;
  64887. this._isOutputConnected = false;
  64888. this._urlType = "Unknown";
  64889. this.name = name;
  64890. this._scene = scene;
  64891. this._readyToPlayCallback = readyToPlayCallback;
  64892. // Default custom attenuation function is a linear attenuation
  64893. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64894. if (currentDistance < maxDistance) {
  64895. return currentVolume * (1 - currentDistance / maxDistance);
  64896. }
  64897. else {
  64898. return 0;
  64899. }
  64900. };
  64901. if (options) {
  64902. this.autoplay = options.autoplay || false;
  64903. this.loop = options.loop || false;
  64904. // if volume === 0, we need another way to check this option
  64905. if (options.volume !== undefined) {
  64906. this._volume = options.volume;
  64907. }
  64908. this.spatialSound = options.spatialSound || false;
  64909. this.maxDistance = options.maxDistance || 100;
  64910. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64911. this.rolloffFactor = options.rolloffFactor || 1;
  64912. this.refDistance = options.refDistance || 1;
  64913. this.distanceModel = options.distanceModel || "linear";
  64914. this._playbackRate = options.playbackRate || 1;
  64915. this._streaming = options.streaming || false;
  64916. }
  64917. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64918. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64919. this._soundGain.gain.value = this._volume;
  64920. this._inputAudioNode = this._soundGain;
  64921. this._outputAudioNode = this._soundGain;
  64922. if (this.spatialSound) {
  64923. this._createSpatialParameters();
  64924. }
  64925. this._scene.mainSoundTrack.AddSound(this);
  64926. var validParameter = true;
  64927. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64928. if (urlOrArrayBuffer) {
  64929. try {
  64930. if (typeof (urlOrArrayBuffer) === "string") {
  64931. this._urlType = "String";
  64932. }
  64933. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64934. this._urlType = "ArrayBuffer";
  64935. }
  64936. else if (urlOrArrayBuffer instanceof MediaStream) {
  64937. this._urlType = "MediaStream";
  64938. }
  64939. else if (Array.isArray(urlOrArrayBuffer)) {
  64940. this._urlType = "Array";
  64941. }
  64942. var urls = [];
  64943. var codecSupportedFound = false;
  64944. switch (this._urlType) {
  64945. case "MediaStream":
  64946. this._streaming = true;
  64947. this._isReadyToPlay = true;
  64948. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  64949. if (this.autoplay) {
  64950. this.play();
  64951. }
  64952. if (this._readyToPlayCallback) {
  64953. this._readyToPlayCallback();
  64954. }
  64955. break;
  64956. case "ArrayBuffer":
  64957. if (urlOrArrayBuffer.byteLength > 0) {
  64958. codecSupportedFound = true;
  64959. this._soundLoaded(urlOrArrayBuffer);
  64960. }
  64961. break;
  64962. case "String":
  64963. urls.push(urlOrArrayBuffer);
  64964. case "Array":
  64965. if (urls.length === 0)
  64966. urls = urlOrArrayBuffer;
  64967. // If we found a supported format, we load it immediately and stop the loop
  64968. for (var i = 0; i < urls.length; i++) {
  64969. var url = urls[i];
  64970. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64971. codecSupportedFound = true;
  64972. }
  64973. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64974. codecSupportedFound = true;
  64975. }
  64976. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64977. codecSupportedFound = true;
  64978. }
  64979. if (url.indexOf("blob:") !== -1) {
  64980. codecSupportedFound = true;
  64981. }
  64982. if (codecSupportedFound) {
  64983. // Loading sound using XHR2
  64984. if (!this._streaming) {
  64985. this._scene._loadFile(url, function (data) {
  64986. _this._soundLoaded(data);
  64987. }, undefined, true, true, function (exception) {
  64988. if (exception) {
  64989. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64990. }
  64991. BABYLON.Tools.Error("Sound creation aborted.");
  64992. _this._scene.mainSoundTrack.RemoveSound(_this);
  64993. });
  64994. }
  64995. // Streaming sound using HTML5 Audio tag
  64996. else {
  64997. this._htmlAudioElement = new Audio(url);
  64998. this._htmlAudioElement.controls = false;
  64999. this._htmlAudioElement.loop = this.loop;
  65000. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65001. this._htmlAudioElement.preload = "auto";
  65002. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65003. _this._isReadyToPlay = true;
  65004. if (_this.autoplay) {
  65005. _this.play();
  65006. }
  65007. if (_this._readyToPlayCallback) {
  65008. _this._readyToPlayCallback();
  65009. }
  65010. });
  65011. document.body.appendChild(this._htmlAudioElement);
  65012. }
  65013. break;
  65014. }
  65015. }
  65016. break;
  65017. default:
  65018. validParameter = false;
  65019. break;
  65020. }
  65021. if (!validParameter) {
  65022. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65023. }
  65024. else {
  65025. if (!codecSupportedFound) {
  65026. this._isReadyToPlay = true;
  65027. // Simulating a ready to play event to avoid breaking code path
  65028. if (this._readyToPlayCallback) {
  65029. window.setTimeout(function () {
  65030. if (_this._readyToPlayCallback) {
  65031. _this._readyToPlayCallback();
  65032. }
  65033. }, 1000);
  65034. }
  65035. }
  65036. }
  65037. }
  65038. catch (ex) {
  65039. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65040. this._scene.mainSoundTrack.RemoveSound(this);
  65041. }
  65042. }
  65043. }
  65044. else {
  65045. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65046. this._scene.mainSoundTrack.AddSound(this);
  65047. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65048. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65049. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65050. }
  65051. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65052. if (this._readyToPlayCallback) {
  65053. window.setTimeout(function () {
  65054. if (_this._readyToPlayCallback) {
  65055. _this._readyToPlayCallback();
  65056. }
  65057. }, 1000);
  65058. }
  65059. }
  65060. }
  65061. Sound.prototype.dispose = function () {
  65062. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65063. if (this.isPlaying) {
  65064. this.stop();
  65065. }
  65066. this._isReadyToPlay = false;
  65067. if (this.soundTrackId === -1) {
  65068. this._scene.mainSoundTrack.RemoveSound(this);
  65069. }
  65070. else {
  65071. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65072. }
  65073. if (this._soundGain) {
  65074. this._soundGain.disconnect();
  65075. this._soundGain = null;
  65076. }
  65077. if (this._soundPanner) {
  65078. this._soundPanner.disconnect();
  65079. this._soundPanner = null;
  65080. }
  65081. if (this._soundSource) {
  65082. this._soundSource.disconnect();
  65083. this._soundSource = null;
  65084. }
  65085. this._audioBuffer = null;
  65086. if (this._htmlAudioElement) {
  65087. this._htmlAudioElement.pause();
  65088. this._htmlAudioElement.src = "";
  65089. document.body.removeChild(this._htmlAudioElement);
  65090. }
  65091. if (this._streamingSource) {
  65092. this._streamingSource.disconnect();
  65093. }
  65094. if (this._connectedMesh && this._registerFunc) {
  65095. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65096. this._connectedMesh = null;
  65097. }
  65098. }
  65099. };
  65100. Sound.prototype.isReady = function () {
  65101. return this._isReadyToPlay;
  65102. };
  65103. Sound.prototype._soundLoaded = function (audioData) {
  65104. var _this = this;
  65105. if (!BABYLON.Engine.audioEngine.audioContext) {
  65106. return;
  65107. }
  65108. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65109. _this._audioBuffer = buffer;
  65110. _this._isReadyToPlay = true;
  65111. if (_this.autoplay) {
  65112. _this.play();
  65113. }
  65114. if (_this._readyToPlayCallback) {
  65115. _this._readyToPlayCallback();
  65116. }
  65117. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65118. };
  65119. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65120. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65121. this._audioBuffer = audioBuffer;
  65122. this._isReadyToPlay = true;
  65123. }
  65124. };
  65125. Sound.prototype.updateOptions = function (options) {
  65126. if (options) {
  65127. this.loop = options.loop || this.loop;
  65128. this.maxDistance = options.maxDistance || this.maxDistance;
  65129. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65130. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65131. this.refDistance = options.refDistance || this.refDistance;
  65132. this.distanceModel = options.distanceModel || this.distanceModel;
  65133. this._playbackRate = options.playbackRate || this._playbackRate;
  65134. this._updateSpatialParameters();
  65135. if (this.isPlaying) {
  65136. if (this._streaming && this._htmlAudioElement) {
  65137. this._htmlAudioElement.playbackRate = this._playbackRate;
  65138. }
  65139. else {
  65140. if (this._soundSource) {
  65141. this._soundSource.playbackRate.value = this._playbackRate;
  65142. }
  65143. }
  65144. }
  65145. }
  65146. };
  65147. Sound.prototype._createSpatialParameters = function () {
  65148. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65149. if (this._scene.headphone) {
  65150. this._panningModel = "HRTF";
  65151. }
  65152. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  65153. this._updateSpatialParameters();
  65154. this._soundPanner.connect(this._outputAudioNode);
  65155. this._inputAudioNode = this._soundPanner;
  65156. }
  65157. };
  65158. Sound.prototype._updateSpatialParameters = function () {
  65159. if (this.spatialSound && this._soundPanner) {
  65160. if (this.useCustomAttenuation) {
  65161. // Tricks to disable in a way embedded Web Audio attenuation
  65162. this._soundPanner.distanceModel = "linear";
  65163. this._soundPanner.maxDistance = Number.MAX_VALUE;
  65164. this._soundPanner.refDistance = 1;
  65165. this._soundPanner.rolloffFactor = 1;
  65166. this._soundPanner.panningModel = this._panningModel;
  65167. }
  65168. else {
  65169. this._soundPanner.distanceModel = this.distanceModel;
  65170. this._soundPanner.maxDistance = this.maxDistance;
  65171. this._soundPanner.refDistance = this.refDistance;
  65172. this._soundPanner.rolloffFactor = this.rolloffFactor;
  65173. this._soundPanner.panningModel = this._panningModel;
  65174. }
  65175. }
  65176. };
  65177. Sound.prototype.switchPanningModelToHRTF = function () {
  65178. this._panningModel = "HRTF";
  65179. this._switchPanningModel();
  65180. };
  65181. Sound.prototype.switchPanningModelToEqualPower = function () {
  65182. this._panningModel = "equalpower";
  65183. this._switchPanningModel();
  65184. };
  65185. Sound.prototype._switchPanningModel = function () {
  65186. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65187. this._soundPanner.panningModel = this._panningModel;
  65188. }
  65189. };
  65190. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  65191. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65192. if (this._isOutputConnected) {
  65193. this._outputAudioNode.disconnect();
  65194. }
  65195. this._outputAudioNode.connect(soundTrackAudioNode);
  65196. this._isOutputConnected = true;
  65197. }
  65198. };
  65199. /**
  65200. * Transform this sound into a directional source
  65201. * @param coneInnerAngle Size of the inner cone in degree
  65202. * @param coneOuterAngle Size of the outer cone in degree
  65203. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  65204. */
  65205. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  65206. if (coneOuterAngle < coneInnerAngle) {
  65207. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  65208. return;
  65209. }
  65210. this._coneInnerAngle = coneInnerAngle;
  65211. this._coneOuterAngle = coneOuterAngle;
  65212. this._coneOuterGain = coneOuterGain;
  65213. this._isDirectional = true;
  65214. if (this.isPlaying && this.loop) {
  65215. this.stop();
  65216. this.play();
  65217. }
  65218. };
  65219. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  65220. /**
  65221. * Gets or sets the inner angle for the directional cone.
  65222. */
  65223. get: function () {
  65224. return this._coneInnerAngle;
  65225. },
  65226. /**
  65227. * Gets or sets the inner angle for the directional cone.
  65228. */
  65229. set: function (value) {
  65230. if (value != this._coneInnerAngle) {
  65231. if (this._coneOuterAngle < value) {
  65232. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65233. return;
  65234. }
  65235. this._coneInnerAngle = value;
  65236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65237. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65238. }
  65239. }
  65240. },
  65241. enumerable: true,
  65242. configurable: true
  65243. });
  65244. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65245. /**
  65246. * Gets or sets the outer angle for the directional cone.
  65247. */
  65248. get: function () {
  65249. return this._coneOuterAngle;
  65250. },
  65251. /**
  65252. * Gets or sets the outer angle for the directional cone.
  65253. */
  65254. set: function (value) {
  65255. if (value != this._coneOuterAngle) {
  65256. if (value < this._coneInnerAngle) {
  65257. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65258. return;
  65259. }
  65260. this._coneOuterAngle = value;
  65261. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65262. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65263. }
  65264. }
  65265. },
  65266. enumerable: true,
  65267. configurable: true
  65268. });
  65269. Sound.prototype.setPosition = function (newPosition) {
  65270. this._position = newPosition;
  65271. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65272. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65273. }
  65274. };
  65275. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65276. this._localDirection = newLocalDirection;
  65277. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65278. this._updateDirection();
  65279. }
  65280. };
  65281. Sound.prototype._updateDirection = function () {
  65282. if (!this._connectedMesh || !this._soundPanner) {
  65283. return;
  65284. }
  65285. var mat = this._connectedMesh.getWorldMatrix();
  65286. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65287. direction.normalize();
  65288. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65289. };
  65290. Sound.prototype.updateDistanceFromListener = function () {
  65291. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65292. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65293. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65294. }
  65295. };
  65296. Sound.prototype.setAttenuationFunction = function (callback) {
  65297. this._customAttenuationFunction = callback;
  65298. };
  65299. /**
  65300. * Play the sound
  65301. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65302. * @param offset (optional) Start the sound setting it at a specific time
  65303. */
  65304. Sound.prototype.play = function (time, offset) {
  65305. var _this = this;
  65306. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65307. try {
  65308. if (this._startOffset < 0) {
  65309. time = -this._startOffset;
  65310. this._startOffset = 0;
  65311. }
  65312. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65313. if (!this._soundSource || !this._streamingSource) {
  65314. if (this.spatialSound && this._soundPanner) {
  65315. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65316. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65317. }
  65318. if (this._isDirectional) {
  65319. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65320. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65321. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65322. if (this._connectedMesh) {
  65323. this._updateDirection();
  65324. }
  65325. else {
  65326. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65327. }
  65328. }
  65329. }
  65330. }
  65331. if (this._streaming) {
  65332. if (!this._streamingSource) {
  65333. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65334. this._htmlAudioElement.onended = function () { _this._onended(); };
  65335. this._htmlAudioElement.playbackRate = this._playbackRate;
  65336. }
  65337. this._streamingSource.disconnect();
  65338. this._streamingSource.connect(this._inputAudioNode);
  65339. if (this._htmlAudioElement) {
  65340. this._htmlAudioElement.play();
  65341. }
  65342. }
  65343. else {
  65344. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65345. this._soundSource.buffer = this._audioBuffer;
  65346. this._soundSource.connect(this._inputAudioNode);
  65347. this._soundSource.loop = this.loop;
  65348. this._soundSource.playbackRate.value = this._playbackRate;
  65349. this._soundSource.onended = function () { _this._onended(); };
  65350. if (this._soundSource.buffer) {
  65351. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65352. }
  65353. }
  65354. this._startTime = startTime;
  65355. this.isPlaying = true;
  65356. this.isPaused = false;
  65357. }
  65358. catch (ex) {
  65359. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65360. }
  65361. }
  65362. };
  65363. Sound.prototype._onended = function () {
  65364. this.isPlaying = false;
  65365. if (this.onended) {
  65366. this.onended();
  65367. }
  65368. this.onEndedObservable.notifyObservers(this);
  65369. };
  65370. /**
  65371. * Stop the sound
  65372. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65373. */
  65374. Sound.prototype.stop = function (time) {
  65375. if (this.isPlaying) {
  65376. if (this._streaming) {
  65377. if (this._htmlAudioElement) {
  65378. this._htmlAudioElement.pause();
  65379. // Test needed for Firefox or it will generate an Invalid State Error
  65380. if (this._htmlAudioElement.currentTime > 0) {
  65381. this._htmlAudioElement.currentTime = 0;
  65382. }
  65383. }
  65384. else {
  65385. this._streamingSource.disconnect();
  65386. }
  65387. }
  65388. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65389. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65390. this._soundSource.stop(stopTime);
  65391. this._soundSource.onended = function () { };
  65392. if (!this.isPaused) {
  65393. this._startOffset = 0;
  65394. }
  65395. }
  65396. this.isPlaying = false;
  65397. }
  65398. };
  65399. Sound.prototype.pause = function () {
  65400. if (this.isPlaying) {
  65401. this.isPaused = true;
  65402. if (this._streaming) {
  65403. if (this._htmlAudioElement) {
  65404. this._htmlAudioElement.pause();
  65405. }
  65406. else {
  65407. this._streamingSource.disconnect();
  65408. }
  65409. }
  65410. else if (BABYLON.Engine.audioEngine.audioContext) {
  65411. this.stop(0);
  65412. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65413. }
  65414. }
  65415. };
  65416. Sound.prototype.setVolume = function (newVolume, time) {
  65417. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65418. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65419. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65420. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65421. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65422. }
  65423. else {
  65424. this._soundGain.gain.value = newVolume;
  65425. }
  65426. }
  65427. this._volume = newVolume;
  65428. };
  65429. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65430. this._playbackRate = newPlaybackRate;
  65431. if (this.isPlaying) {
  65432. if (this._streaming && this._htmlAudioElement) {
  65433. this._htmlAudioElement.playbackRate = this._playbackRate;
  65434. }
  65435. else if (this._soundSource) {
  65436. this._soundSource.playbackRate.value = this._playbackRate;
  65437. }
  65438. }
  65439. };
  65440. Sound.prototype.getVolume = function () {
  65441. return this._volume;
  65442. };
  65443. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65444. var _this = this;
  65445. if (this._connectedMesh && this._registerFunc) {
  65446. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65447. this._registerFunc = null;
  65448. }
  65449. this._connectedMesh = meshToConnectTo;
  65450. if (!this.spatialSound) {
  65451. this.spatialSound = true;
  65452. this._createSpatialParameters();
  65453. if (this.isPlaying && this.loop) {
  65454. this.stop();
  65455. this.play();
  65456. }
  65457. }
  65458. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65459. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65460. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65461. };
  65462. Sound.prototype.detachFromMesh = function () {
  65463. if (this._connectedMesh && this._registerFunc) {
  65464. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65465. this._registerFunc = null;
  65466. this._connectedMesh = null;
  65467. }
  65468. };
  65469. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65470. if (!node.getBoundingInfo) {
  65471. return;
  65472. }
  65473. var mesh = node;
  65474. if (this._positionInEmitterSpace) {
  65475. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65476. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65477. }
  65478. else {
  65479. var boundingInfo = mesh.getBoundingInfo();
  65480. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65481. }
  65482. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65483. this._updateDirection();
  65484. }
  65485. };
  65486. Sound.prototype.clone = function () {
  65487. var _this = this;
  65488. if (!this._streaming) {
  65489. var setBufferAndRun = function () {
  65490. if (_this._isReadyToPlay) {
  65491. clonedSound._audioBuffer = _this.getAudioBuffer();
  65492. clonedSound._isReadyToPlay = true;
  65493. if (clonedSound.autoplay) {
  65494. clonedSound.play();
  65495. }
  65496. }
  65497. else {
  65498. window.setTimeout(setBufferAndRun, 300);
  65499. }
  65500. };
  65501. var currentOptions = {
  65502. autoplay: this.autoplay, loop: this.loop,
  65503. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65504. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65505. refDistance: this.refDistance, distanceModel: this.distanceModel
  65506. };
  65507. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65508. if (this.useCustomAttenuation) {
  65509. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65510. }
  65511. clonedSound.setPosition(this._position);
  65512. clonedSound.setPlaybackRate(this._playbackRate);
  65513. setBufferAndRun();
  65514. return clonedSound;
  65515. }
  65516. // Can't clone a streaming sound
  65517. else {
  65518. return null;
  65519. }
  65520. };
  65521. Sound.prototype.getAudioBuffer = function () {
  65522. return this._audioBuffer;
  65523. };
  65524. Sound.prototype.serialize = function () {
  65525. var serializationObject = {
  65526. name: this.name,
  65527. url: this.name,
  65528. autoplay: this.autoplay,
  65529. loop: this.loop,
  65530. volume: this._volume,
  65531. spatialSound: this.spatialSound,
  65532. maxDistance: this.maxDistance,
  65533. rolloffFactor: this.rolloffFactor,
  65534. refDistance: this.refDistance,
  65535. distanceModel: this.distanceModel,
  65536. playbackRate: this._playbackRate,
  65537. panningModel: this._panningModel,
  65538. soundTrackId: this.soundTrackId
  65539. };
  65540. if (this.spatialSound) {
  65541. if (this._connectedMesh)
  65542. serializationObject.connectedMeshId = this._connectedMesh.id;
  65543. serializationObject.position = this._position.asArray();
  65544. serializationObject.refDistance = this.refDistance;
  65545. serializationObject.distanceModel = this.distanceModel;
  65546. serializationObject.isDirectional = this._isDirectional;
  65547. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65548. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65549. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65550. serializationObject.coneOuterGain = this._coneOuterGain;
  65551. }
  65552. return serializationObject;
  65553. };
  65554. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65555. var soundName = parsedSound.name;
  65556. var soundUrl;
  65557. if (parsedSound.url) {
  65558. soundUrl = rootUrl + parsedSound.url;
  65559. }
  65560. else {
  65561. soundUrl = rootUrl + soundName;
  65562. }
  65563. var options = {
  65564. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65565. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65566. rolloffFactor: parsedSound.rolloffFactor,
  65567. refDistance: parsedSound.refDistance,
  65568. distanceModel: parsedSound.distanceModel,
  65569. playbackRate: parsedSound.playbackRate
  65570. };
  65571. var newSound;
  65572. if (!sourceSound) {
  65573. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65574. scene._addPendingData(newSound);
  65575. }
  65576. else {
  65577. var setBufferAndRun = function () {
  65578. if (sourceSound._isReadyToPlay) {
  65579. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65580. newSound._isReadyToPlay = true;
  65581. if (newSound.autoplay) {
  65582. newSound.play();
  65583. }
  65584. }
  65585. else {
  65586. window.setTimeout(setBufferAndRun, 300);
  65587. }
  65588. };
  65589. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65590. setBufferAndRun();
  65591. }
  65592. if (parsedSound.position) {
  65593. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65594. newSound.setPosition(soundPosition);
  65595. }
  65596. if (parsedSound.isDirectional) {
  65597. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65598. if (parsedSound.localDirectionToMesh) {
  65599. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65600. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65601. }
  65602. }
  65603. if (parsedSound.connectedMeshId) {
  65604. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65605. if (connectedMesh) {
  65606. newSound.attachToMesh(connectedMesh);
  65607. }
  65608. }
  65609. return newSound;
  65610. };
  65611. return Sound;
  65612. }());
  65613. BABYLON.Sound = Sound;
  65614. })(BABYLON || (BABYLON = {}));
  65615. //# sourceMappingURL=babylon.sound.js.map
  65616. var BABYLON;
  65617. (function (BABYLON) {
  65618. var SoundTrack = /** @class */ (function () {
  65619. function SoundTrack(scene, options) {
  65620. this.id = -1;
  65621. this._isMainTrack = false;
  65622. this._isInitialized = false;
  65623. this._scene = scene;
  65624. this.soundCollection = new Array();
  65625. this._options = options;
  65626. if (!this._isMainTrack) {
  65627. this._scene.soundTracks.push(this);
  65628. this.id = this._scene.soundTracks.length - 1;
  65629. }
  65630. }
  65631. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65632. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65633. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65634. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65635. if (this._options) {
  65636. if (this._options.volume) {
  65637. this._outputAudioNode.gain.value = this._options.volume;
  65638. }
  65639. if (this._options.mainTrack) {
  65640. this._isMainTrack = this._options.mainTrack;
  65641. }
  65642. }
  65643. this._isInitialized = true;
  65644. }
  65645. };
  65646. SoundTrack.prototype.dispose = function () {
  65647. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65648. if (this._connectedAnalyser) {
  65649. this._connectedAnalyser.stopDebugCanvas();
  65650. }
  65651. while (this.soundCollection.length) {
  65652. this.soundCollection[0].dispose();
  65653. }
  65654. if (this._outputAudioNode) {
  65655. this._outputAudioNode.disconnect();
  65656. }
  65657. this._outputAudioNode = null;
  65658. }
  65659. };
  65660. SoundTrack.prototype.AddSound = function (sound) {
  65661. if (!this._isInitialized) {
  65662. this._initializeSoundTrackAudioGraph();
  65663. }
  65664. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65665. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65666. }
  65667. if (sound.soundTrackId) {
  65668. if (sound.soundTrackId === -1) {
  65669. this._scene.mainSoundTrack.RemoveSound(sound);
  65670. }
  65671. else {
  65672. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65673. }
  65674. }
  65675. this.soundCollection.push(sound);
  65676. sound.soundTrackId = this.id;
  65677. };
  65678. SoundTrack.prototype.RemoveSound = function (sound) {
  65679. var index = this.soundCollection.indexOf(sound);
  65680. if (index !== -1) {
  65681. this.soundCollection.splice(index, 1);
  65682. }
  65683. };
  65684. SoundTrack.prototype.setVolume = function (newVolume) {
  65685. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65686. this._outputAudioNode.gain.value = newVolume;
  65687. }
  65688. };
  65689. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65690. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65691. for (var i = 0; i < this.soundCollection.length; i++) {
  65692. this.soundCollection[i].switchPanningModelToHRTF();
  65693. }
  65694. }
  65695. };
  65696. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65697. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65698. for (var i = 0; i < this.soundCollection.length; i++) {
  65699. this.soundCollection[i].switchPanningModelToEqualPower();
  65700. }
  65701. }
  65702. };
  65703. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65704. if (this._connectedAnalyser) {
  65705. this._connectedAnalyser.stopDebugCanvas();
  65706. }
  65707. this._connectedAnalyser = analyser;
  65708. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65709. this._outputAudioNode.disconnect();
  65710. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65711. }
  65712. };
  65713. return SoundTrack;
  65714. }());
  65715. BABYLON.SoundTrack = SoundTrack;
  65716. })(BABYLON || (BABYLON = {}));
  65717. //# sourceMappingURL=babylon.soundtrack.js.map
  65718. var BABYLON;
  65719. (function (BABYLON) {
  65720. /**
  65721. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65722. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65723. */
  65724. var Analyser = /** @class */ (function () {
  65725. /**
  65726. * Creates a new analyser
  65727. * @param scene defines hosting scene
  65728. */
  65729. function Analyser(scene) {
  65730. /**
  65731. * Gets or sets the smoothing
  65732. * @ignorenaming
  65733. */
  65734. this.SMOOTHING = 0.75;
  65735. /**
  65736. * Gets or sets the FFT table size
  65737. * @ignorenaming
  65738. */
  65739. this.FFT_SIZE = 512;
  65740. /**
  65741. * Gets or sets the bar graph amplitude
  65742. * @ignorenaming
  65743. */
  65744. this.BARGRAPHAMPLITUDE = 256;
  65745. /**
  65746. * Gets or sets the position of the debug canvas
  65747. * @ignorenaming
  65748. */
  65749. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65750. /**
  65751. * Gets or sets the debug canvas size
  65752. * @ignorenaming
  65753. */
  65754. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65755. this._scene = scene;
  65756. this._audioEngine = BABYLON.Engine.audioEngine;
  65757. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65758. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65759. this._webAudioAnalyser.minDecibels = -140;
  65760. this._webAudioAnalyser.maxDecibels = 0;
  65761. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65762. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65763. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65764. }
  65765. }
  65766. /**
  65767. * Get the number of data values you will have to play with for the visualization
  65768. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65769. * @returns a number
  65770. */
  65771. Analyser.prototype.getFrequencyBinCount = function () {
  65772. if (this._audioEngine.canUseWebAudio) {
  65773. return this._webAudioAnalyser.frequencyBinCount;
  65774. }
  65775. else {
  65776. return 0;
  65777. }
  65778. };
  65779. /**
  65780. * Gets the current frequency data as a byte array
  65781. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65782. * @returns a Uint8Array
  65783. */
  65784. Analyser.prototype.getByteFrequencyData = function () {
  65785. if (this._audioEngine.canUseWebAudio) {
  65786. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65787. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65788. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65789. }
  65790. return this._byteFreqs;
  65791. };
  65792. /**
  65793. * Gets the current waveform as a byte array
  65794. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65795. * @returns a Uint8Array
  65796. */
  65797. Analyser.prototype.getByteTimeDomainData = function () {
  65798. if (this._audioEngine.canUseWebAudio) {
  65799. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65800. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65801. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65802. }
  65803. return this._byteTime;
  65804. };
  65805. /**
  65806. * Gets the current frequency data as a float array
  65807. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65808. * @returns a Float32Array
  65809. */
  65810. Analyser.prototype.getFloatFrequencyData = function () {
  65811. if (this._audioEngine.canUseWebAudio) {
  65812. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65813. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65814. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65815. }
  65816. return this._floatFreqs;
  65817. };
  65818. /**
  65819. * Renders the debug canvas
  65820. */
  65821. Analyser.prototype.drawDebugCanvas = function () {
  65822. var _this = this;
  65823. if (this._audioEngine.canUseWebAudio) {
  65824. if (!this._debugCanvas) {
  65825. this._debugCanvas = document.createElement("canvas");
  65826. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65827. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65828. this._debugCanvas.style.position = "absolute";
  65829. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65830. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65831. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65832. document.body.appendChild(this._debugCanvas);
  65833. this._registerFunc = function () {
  65834. _this.drawDebugCanvas();
  65835. };
  65836. this._scene.registerBeforeRender(this._registerFunc);
  65837. }
  65838. if (this._registerFunc && this._debugCanvasContext) {
  65839. var workingArray = this.getByteFrequencyData();
  65840. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65841. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65842. // Draw the frequency domain chart.
  65843. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65844. var value = workingArray[i];
  65845. var percent = value / this.BARGRAPHAMPLITUDE;
  65846. var height = this.DEBUGCANVASSIZE.height * percent;
  65847. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65848. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65849. var hue = i / this.getFrequencyBinCount() * 360;
  65850. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65851. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65852. }
  65853. }
  65854. }
  65855. };
  65856. /**
  65857. * Stops rendering the debug canvas and removes it
  65858. */
  65859. Analyser.prototype.stopDebugCanvas = function () {
  65860. if (this._debugCanvas) {
  65861. if (this._registerFunc) {
  65862. this._scene.unregisterBeforeRender(this._registerFunc);
  65863. this._registerFunc = null;
  65864. }
  65865. document.body.removeChild(this._debugCanvas);
  65866. this._debugCanvas = null;
  65867. this._debugCanvasContext = null;
  65868. }
  65869. };
  65870. /**
  65871. * Connects two audio nodes
  65872. * @param inputAudioNode defines first node to connect
  65873. * @param outputAudioNode defines second node to connect
  65874. */
  65875. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65876. if (this._audioEngine.canUseWebAudio) {
  65877. inputAudioNode.connect(this._webAudioAnalyser);
  65878. this._webAudioAnalyser.connect(outputAudioNode);
  65879. }
  65880. };
  65881. /**
  65882. * Releases all associated resources
  65883. */
  65884. Analyser.prototype.dispose = function () {
  65885. if (this._audioEngine.canUseWebAudio) {
  65886. this._webAudioAnalyser.disconnect();
  65887. }
  65888. };
  65889. return Analyser;
  65890. }());
  65891. BABYLON.Analyser = Analyser;
  65892. })(BABYLON || (BABYLON = {}));
  65893. //# sourceMappingURL=babylon.analyser.js.map
  65894. var BABYLON;
  65895. (function (BABYLON) {
  65896. /**
  65897. * Wraps one or more Sound objects and selects one with random weight for playback.
  65898. */
  65899. var WeightedSound = /** @class */ (function () {
  65900. /**
  65901. * Creates a new WeightedSound from the list of sounds given.
  65902. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  65903. * @param sounds Array of Sounds that will be selected from.
  65904. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  65905. */
  65906. function WeightedSound(loop, sounds, weights) {
  65907. var _this = this;
  65908. /** When true a Sound will be selected and played when the current playing Sound completes. */
  65909. this.loop = false;
  65910. this._coneInnerAngle = 360;
  65911. this._coneOuterAngle = 360;
  65912. this._volume = 1;
  65913. /** A Sound is currently playing. */
  65914. this.isPlaying = false;
  65915. /** A Sound is currently paused. */
  65916. this.isPaused = false;
  65917. this._sounds = [];
  65918. this._weights = [];
  65919. if (sounds.length !== weights.length) {
  65920. throw new Error('Sounds length does not equal weights length');
  65921. }
  65922. this.loop = loop;
  65923. this._weights = weights;
  65924. // Normalize the weights
  65925. var weightSum = 0;
  65926. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65927. var weight = weights_1[_i];
  65928. weightSum += weight;
  65929. }
  65930. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65931. for (var i = 0; i < this._weights.length; i++) {
  65932. this._weights[i] *= invWeightSum;
  65933. }
  65934. this._sounds = sounds;
  65935. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65936. var sound = _b[_a];
  65937. sound.onEndedObservable.add(function () { _this._onended(); });
  65938. }
  65939. }
  65940. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65941. /**
  65942. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65943. */
  65944. get: function () {
  65945. return this._coneInnerAngle;
  65946. },
  65947. /**
  65948. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65949. */
  65950. set: function (value) {
  65951. if (value !== this._coneInnerAngle) {
  65952. if (this._coneOuterAngle < value) {
  65953. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65954. return;
  65955. }
  65956. this._coneInnerAngle = value;
  65957. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65958. var sound = _a[_i];
  65959. sound.directionalConeInnerAngle = value;
  65960. }
  65961. }
  65962. },
  65963. enumerable: true,
  65964. configurable: true
  65965. });
  65966. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65967. /**
  65968. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65969. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65970. */
  65971. get: function () {
  65972. return this._coneOuterAngle;
  65973. },
  65974. /**
  65975. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65976. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65977. */
  65978. set: function (value) {
  65979. if (value !== this._coneOuterAngle) {
  65980. if (value < this._coneInnerAngle) {
  65981. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65982. return;
  65983. }
  65984. this._coneOuterAngle = value;
  65985. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65986. var sound = _a[_i];
  65987. sound.directionalConeOuterAngle = value;
  65988. }
  65989. }
  65990. },
  65991. enumerable: true,
  65992. configurable: true
  65993. });
  65994. Object.defineProperty(WeightedSound.prototype, "volume", {
  65995. /**
  65996. * Playback volume.
  65997. */
  65998. get: function () {
  65999. return this._volume;
  66000. },
  66001. /**
  66002. * Playback volume.
  66003. */
  66004. set: function (value) {
  66005. if (value !== this._volume) {
  66006. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66007. var sound = _a[_i];
  66008. sound.setVolume(value);
  66009. }
  66010. }
  66011. },
  66012. enumerable: true,
  66013. configurable: true
  66014. });
  66015. WeightedSound.prototype._onended = function () {
  66016. if (this._currentIndex !== undefined) {
  66017. this._sounds[this._currentIndex].autoplay = false;
  66018. }
  66019. if (this.loop && this.isPlaying) {
  66020. this.play();
  66021. }
  66022. else {
  66023. this.isPlaying = false;
  66024. }
  66025. };
  66026. /**
  66027. * Suspend playback
  66028. */
  66029. WeightedSound.prototype.pause = function () {
  66030. this.isPaused = true;
  66031. if (this._currentIndex !== undefined) {
  66032. this._sounds[this._currentIndex].pause();
  66033. }
  66034. };
  66035. /**
  66036. * Stop playback
  66037. */
  66038. WeightedSound.prototype.stop = function () {
  66039. this.isPlaying = false;
  66040. if (this._currentIndex !== undefined) {
  66041. this._sounds[this._currentIndex].stop();
  66042. }
  66043. };
  66044. /**
  66045. * Start playback.
  66046. * @param startOffset Position the clip head at a specific time in seconds.
  66047. */
  66048. WeightedSound.prototype.play = function (startOffset) {
  66049. if (!this.isPaused) {
  66050. this.stop();
  66051. var randomValue = Math.random();
  66052. var total = 0;
  66053. for (var i = 0; i < this._weights.length; i++) {
  66054. total += this._weights[i];
  66055. if (randomValue <= total) {
  66056. this._currentIndex = i;
  66057. break;
  66058. }
  66059. }
  66060. }
  66061. var sound = this._sounds[this._currentIndex];
  66062. if (sound.isReady()) {
  66063. sound.play(0, this.isPaused ? undefined : startOffset);
  66064. }
  66065. else {
  66066. sound.autoplay = true;
  66067. }
  66068. this.isPlaying = true;
  66069. this.isPaused = false;
  66070. };
  66071. return WeightedSound;
  66072. }());
  66073. BABYLON.WeightedSound = WeightedSound;
  66074. })(BABYLON || (BABYLON = {}));
  66075. //# sourceMappingURL=babylon.weightedsound.js.map
  66076. var BABYLON;
  66077. (function (BABYLON) {
  66078. var CubeTexture = /** @class */ (function (_super) {
  66079. __extends(CubeTexture, _super);
  66080. /**
  66081. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66082. * as prefiltered data.
  66083. * @param rootUrl defines the url of the texture or the root name of the six images
  66084. * @param scene defines the scene the texture is attached to
  66085. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66086. * @param noMipmap defines if mipmaps should be created or not
  66087. * @param files defines the six files to load for the different faces
  66088. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66089. * @param onError defines a callback triggered in case of error during load
  66090. * @param format defines the internal format to use for the texture once loaded
  66091. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66092. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66093. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66094. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66095. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66096. * @return the cube texture
  66097. */
  66098. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66099. if (extensions === void 0) { extensions = null; }
  66100. if (noMipmap === void 0) { noMipmap = false; }
  66101. if (files === void 0) { files = null; }
  66102. if (onLoad === void 0) { onLoad = null; }
  66103. if (onError === void 0) { onError = null; }
  66104. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66105. if (prefiltered === void 0) { prefiltered = false; }
  66106. if (forcedExtension === void 0) { forcedExtension = null; }
  66107. if (createPolynomials === void 0) { createPolynomials = false; }
  66108. if (lodScale === void 0) { lodScale = 0.8; }
  66109. if (lodOffset === void 0) { lodOffset = 0; }
  66110. var _this = _super.call(this, scene) || this;
  66111. /**
  66112. * Gets or sets the center of the bounding box associated with the cube texture
  66113. * It must define where the camera used to render the texture was set
  66114. */
  66115. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66116. _this._rotationY = 0;
  66117. /** @hidden */
  66118. _this._prefiltered = false;
  66119. _this.name = rootUrl;
  66120. _this.url = rootUrl;
  66121. _this._noMipmap = noMipmap;
  66122. _this.hasAlpha = false;
  66123. _this._format = format;
  66124. _this.isCube = true;
  66125. _this._textureMatrix = BABYLON.Matrix.Identity();
  66126. _this._createPolynomials = createPolynomials;
  66127. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66128. if (!rootUrl && !files) {
  66129. return _this;
  66130. }
  66131. var lastDot = rootUrl.lastIndexOf(".");
  66132. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66133. var isDDS = (extension === ".dds");
  66134. var isEnv = (extension === ".env");
  66135. if (isEnv) {
  66136. _this.gammaSpace = false;
  66137. _this._prefiltered = false;
  66138. }
  66139. else {
  66140. _this._prefiltered = prefiltered;
  66141. if (prefiltered) {
  66142. _this.gammaSpace = false;
  66143. }
  66144. }
  66145. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  66146. if (!files) {
  66147. if (!isEnv && !isDDS && !extensions) {
  66148. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  66149. }
  66150. files = [];
  66151. if (extensions) {
  66152. for (var index = 0; index < extensions.length; index++) {
  66153. files.push(rootUrl + extensions[index]);
  66154. }
  66155. }
  66156. }
  66157. _this._files = files;
  66158. if (!_this._texture) {
  66159. if (!scene.useDelayedTextureLoading) {
  66160. if (prefiltered) {
  66161. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  66162. }
  66163. else {
  66164. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  66165. }
  66166. }
  66167. else {
  66168. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  66169. }
  66170. }
  66171. else if (onLoad) {
  66172. if (_this._texture.isReady) {
  66173. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  66174. }
  66175. else {
  66176. _this._texture.onLoadedObservable.add(onLoad);
  66177. }
  66178. }
  66179. return _this;
  66180. }
  66181. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  66182. get: function () {
  66183. return this._boundingBoxSize;
  66184. },
  66185. /**
  66186. * Gets or sets the size of the bounding box associated with the cube texture
  66187. * When defined, the cubemap will switch to local mode
  66188. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66189. * @example https://www.babylonjs-playground.com/#RNASML
  66190. */
  66191. set: function (value) {
  66192. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66193. return;
  66194. }
  66195. this._boundingBoxSize = value;
  66196. var scene = this.getScene();
  66197. if (scene) {
  66198. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66199. }
  66200. },
  66201. enumerable: true,
  66202. configurable: true
  66203. });
  66204. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  66205. /**
  66206. * Gets texture matrix rotation angle around Y axis radians.
  66207. */
  66208. get: function () {
  66209. return this._rotationY;
  66210. },
  66211. /**
  66212. * Sets texture matrix rotation angle around Y axis in radians.
  66213. */
  66214. set: function (value) {
  66215. this._rotationY = value;
  66216. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  66217. },
  66218. enumerable: true,
  66219. configurable: true
  66220. });
  66221. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  66222. var rootUrlKey = "";
  66223. files.forEach(function (url) { return rootUrlKey += url; });
  66224. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  66225. };
  66226. /**
  66227. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  66228. * @param url defines the url of the prefiltered texture
  66229. * @param scene defines the scene the texture is attached to
  66230. * @param forcedExtension defines the extension of the file if different from the url
  66231. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66232. * @return the prefiltered texture
  66233. */
  66234. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  66235. if (forcedExtension === void 0) { forcedExtension = null; }
  66236. if (createPolynomials === void 0) { createPolynomials = true; }
  66237. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  66238. };
  66239. // Methods
  66240. CubeTexture.prototype.delayLoad = function () {
  66241. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66242. return;
  66243. }
  66244. var scene = this.getScene();
  66245. if (!scene) {
  66246. return;
  66247. }
  66248. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66249. this._texture = this._getFromCache(this.url, this._noMipmap);
  66250. if (!this._texture) {
  66251. if (this._prefiltered) {
  66252. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66253. }
  66254. else {
  66255. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66256. }
  66257. }
  66258. };
  66259. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66260. return this._textureMatrix;
  66261. };
  66262. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66263. this._textureMatrix = value;
  66264. };
  66265. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66266. var texture = BABYLON.SerializationHelper.Parse(function () {
  66267. var prefiltered = false;
  66268. if (parsedTexture.prefiltered) {
  66269. prefiltered = parsedTexture.prefiltered;
  66270. }
  66271. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66272. }, parsedTexture, scene);
  66273. // Local Cubemaps
  66274. if (parsedTexture.boundingBoxPosition) {
  66275. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66276. }
  66277. if (parsedTexture.boundingBoxSize) {
  66278. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66279. }
  66280. // Animations
  66281. if (parsedTexture.animations) {
  66282. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66283. var parsedAnimation = parsedTexture.animations[animationIndex];
  66284. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66285. }
  66286. }
  66287. return texture;
  66288. };
  66289. CubeTexture.prototype.clone = function () {
  66290. var _this = this;
  66291. return BABYLON.SerializationHelper.Clone(function () {
  66292. var scene = _this.getScene();
  66293. if (!scene) {
  66294. return _this;
  66295. }
  66296. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66297. }, this);
  66298. };
  66299. __decorate([
  66300. BABYLON.serialize("rotationY")
  66301. ], CubeTexture.prototype, "rotationY", null);
  66302. return CubeTexture;
  66303. }(BABYLON.BaseTexture));
  66304. BABYLON.CubeTexture = CubeTexture;
  66305. })(BABYLON || (BABYLON = {}));
  66306. //# sourceMappingURL=babylon.cubeTexture.js.map
  66307. var BABYLON;
  66308. (function (BABYLON) {
  66309. /**
  66310. * Raw cube texture where the raw buffers are passed in
  66311. */
  66312. var RawCubeTexture = /** @class */ (function (_super) {
  66313. __extends(RawCubeTexture, _super);
  66314. /**
  66315. * Creates a cube texture where the raw buffers are passed in.
  66316. * @param scene defines the scene the texture is attached to
  66317. * @param data defines the array of data to use to create each face
  66318. * @param size defines the size of the textures
  66319. * @param format defines the format of the data
  66320. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66321. * @param generateMipMaps defines if the engine should generate the mip levels
  66322. * @param invertY defines if data must be stored with Y axis inverted
  66323. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66324. * @param compression defines the compression used (null by default)
  66325. */
  66326. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66327. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66328. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66329. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66330. if (invertY === void 0) { invertY = false; }
  66331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66332. if (compression === void 0) { compression = null; }
  66333. var _this = _super.call(this, "", scene) || this;
  66334. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66335. return _this;
  66336. }
  66337. /**
  66338. * Updates the raw cube texture.
  66339. * @param data defines the data to store
  66340. * @param format defines the data format
  66341. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66342. * @param invertY defines if data must be stored with Y axis inverted
  66343. * @param compression defines the compression used (null by default)
  66344. * @param level defines which level of the texture to update
  66345. */
  66346. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66347. if (compression === void 0) { compression = null; }
  66348. if (level === void 0) { level = 0; }
  66349. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66350. };
  66351. /**
  66352. * Updates a raw cube texture with RGBD encoded data.
  66353. * @param data defines the array of data [mipmap][face] to use to create each face
  66354. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66355. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66356. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66357. * @returns a promsie that resolves when the operation is complete
  66358. */
  66359. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66360. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66361. if (lodScale === void 0) { lodScale = 0.8; }
  66362. if (lodOffset === void 0) { lodOffset = 0; }
  66363. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66364. };
  66365. /**
  66366. * Clones the raw cube texture.
  66367. * @return a new cube texture
  66368. */
  66369. RawCubeTexture.prototype.clone = function () {
  66370. var _this = this;
  66371. return BABYLON.SerializationHelper.Clone(function () {
  66372. var scene = _this.getScene();
  66373. var internalTexture = _this._texture;
  66374. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66375. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66376. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66377. }
  66378. return texture;
  66379. }, this);
  66380. };
  66381. /** @hidden */
  66382. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66383. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66384. internalTexture._bufferViewArrayArray = data;
  66385. internalTexture._lodGenerationScale = lodScale;
  66386. internalTexture._lodGenerationOffset = lodOffset;
  66387. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66388. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66389. internalTexture.isReady = true;
  66390. });
  66391. };
  66392. return RawCubeTexture;
  66393. }(BABYLON.CubeTexture));
  66394. BABYLON.RawCubeTexture = RawCubeTexture;
  66395. })(BABYLON || (BABYLON = {}));
  66396. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66397. var BABYLON;
  66398. (function (BABYLON) {
  66399. var RenderTargetTexture = /** @class */ (function (_super) {
  66400. __extends(RenderTargetTexture, _super);
  66401. /**
  66402. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66403. * or used a shadow, depth texture...
  66404. * @param name The friendly name of the texture
  66405. * @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)
  66406. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66407. * @param generateMipMaps True if mip maps need to be generated after render.
  66408. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66409. * @param type The type of the buffer in the RTT (int, half float, float...)
  66410. * @param isCube True if a cube texture needs to be created
  66411. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66412. * @param generateDepthBuffer True to generate a depth buffer
  66413. * @param generateStencilBuffer True to generate a stencil buffer
  66414. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66415. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66416. */
  66417. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66418. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66419. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66420. if (isCube === void 0) { isCube = false; }
  66421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66422. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66423. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66424. if (isMulti === void 0) { isMulti = false; }
  66425. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66426. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66427. _this.isCube = isCube;
  66428. _this.renderParticles = true;
  66429. _this.renderSprites = false;
  66430. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66431. _this.ignoreCameraViewport = false;
  66432. // Events
  66433. /**
  66434. * An event triggered when the texture is unbind.
  66435. */
  66436. _this.onBeforeBindObservable = new BABYLON.Observable();
  66437. /**
  66438. * An event triggered when the texture is unbind.
  66439. */
  66440. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66441. /**
  66442. * An event triggered before rendering the texture
  66443. */
  66444. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66445. /**
  66446. * An event triggered after rendering the texture
  66447. */
  66448. _this.onAfterRenderObservable = new BABYLON.Observable();
  66449. /**
  66450. * An event triggered after the texture clear
  66451. */
  66452. _this.onClearObservable = new BABYLON.Observable();
  66453. _this._currentRefreshId = -1;
  66454. _this._refreshRate = 1;
  66455. _this._samples = 1;
  66456. /**
  66457. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66458. * It must define where the camera used to render the texture is set
  66459. */
  66460. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66461. scene = _this.getScene();
  66462. if (!scene) {
  66463. return _this;
  66464. }
  66465. _this.renderList = new Array();
  66466. _this._engine = scene.getEngine();
  66467. _this.name = name;
  66468. _this.isRenderTarget = true;
  66469. _this._initialSizeParameter = size;
  66470. _this._processSizeParameter(size);
  66471. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66472. });
  66473. _this._generateMipMaps = generateMipMaps ? true : false;
  66474. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66475. // Rendering groups
  66476. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66477. _this._renderingManager._useSceneAutoClearSetup = true;
  66478. if (isMulti) {
  66479. return _this;
  66480. }
  66481. _this._renderTargetOptions = {
  66482. generateMipMaps: generateMipMaps,
  66483. type: type,
  66484. format: format,
  66485. samplingMode: samplingMode,
  66486. generateDepthBuffer: generateDepthBuffer,
  66487. generateStencilBuffer: generateStencilBuffer
  66488. };
  66489. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66490. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66491. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66492. }
  66493. if (isCube) {
  66494. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66495. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66496. _this._textureMatrix = BABYLON.Matrix.Identity();
  66497. }
  66498. else {
  66499. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66500. }
  66501. return _this;
  66502. }
  66503. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66504. get: function () {
  66505. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66506. },
  66507. enumerable: true,
  66508. configurable: true
  66509. });
  66510. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66511. get: function () {
  66512. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66513. },
  66514. enumerable: true,
  66515. configurable: true
  66516. });
  66517. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66518. get: function () {
  66519. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66520. },
  66521. enumerable: true,
  66522. configurable: true
  66523. });
  66524. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66525. /**
  66526. * Use this list to define the list of mesh you want to render.
  66527. */
  66528. get: function () {
  66529. return this._renderList;
  66530. },
  66531. set: function (value) {
  66532. this._renderList = value;
  66533. if (this._renderList) {
  66534. this._hookArray(this._renderList);
  66535. }
  66536. },
  66537. enumerable: true,
  66538. configurable: true
  66539. });
  66540. RenderTargetTexture.prototype._hookArray = function (array) {
  66541. var _this = this;
  66542. var oldPush = array.push;
  66543. array.push = function () {
  66544. var items = [];
  66545. for (var _i = 0; _i < arguments.length; _i++) {
  66546. items[_i] = arguments[_i];
  66547. }
  66548. var result = oldPush.apply(array, items);
  66549. _this.getScene().meshes.forEach(function (mesh) {
  66550. mesh._markSubMeshesAsLightDirty();
  66551. });
  66552. return result;
  66553. };
  66554. var oldSplice = array.splice;
  66555. array.splice = function (index, deleteCount) {
  66556. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66557. _this.getScene().meshes.forEach(function (mesh) {
  66558. mesh._markSubMeshesAsLightDirty();
  66559. });
  66560. return deleted;
  66561. };
  66562. };
  66563. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66564. set: function (callback) {
  66565. if (this._onAfterUnbindObserver) {
  66566. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66567. }
  66568. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66569. },
  66570. enumerable: true,
  66571. configurable: true
  66572. });
  66573. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66574. set: function (callback) {
  66575. if (this._onBeforeRenderObserver) {
  66576. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66577. }
  66578. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66584. set: function (callback) {
  66585. if (this._onAfterRenderObserver) {
  66586. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66587. }
  66588. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66589. },
  66590. enumerable: true,
  66591. configurable: true
  66592. });
  66593. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66594. set: function (callback) {
  66595. if (this._onClearObserver) {
  66596. this.onClearObservable.remove(this._onClearObserver);
  66597. }
  66598. this._onClearObserver = this.onClearObservable.add(callback);
  66599. },
  66600. enumerable: true,
  66601. configurable: true
  66602. });
  66603. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66604. get: function () {
  66605. return this._renderTargetOptions;
  66606. },
  66607. enumerable: true,
  66608. configurable: true
  66609. });
  66610. RenderTargetTexture.prototype._onRatioRescale = function () {
  66611. if (this._sizeRatio) {
  66612. this.resize(this._initialSizeParameter);
  66613. }
  66614. };
  66615. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66616. get: function () {
  66617. return this._boundingBoxSize;
  66618. },
  66619. /**
  66620. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66621. * When defined, the cubemap will switch to local mode
  66622. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66623. * @example https://www.babylonjs-playground.com/#RNASML
  66624. */
  66625. set: function (value) {
  66626. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66627. return;
  66628. }
  66629. this._boundingBoxSize = value;
  66630. var scene = this.getScene();
  66631. if (scene) {
  66632. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66633. }
  66634. },
  66635. enumerable: true,
  66636. configurable: true
  66637. });
  66638. /**
  66639. * Creates a depth stencil texture.
  66640. * This is only available in WebGL 2 or with the depth texture extension available.
  66641. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66642. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66643. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66644. */
  66645. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66646. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66647. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66648. if (generateStencil === void 0) { generateStencil = false; }
  66649. if (!this.getScene()) {
  66650. return;
  66651. }
  66652. var engine = this.getScene().getEngine();
  66653. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66654. bilinearFiltering: bilinearFiltering,
  66655. comparisonFunction: comparisonFunction,
  66656. generateStencil: generateStencil,
  66657. isCube: this.isCube
  66658. });
  66659. engine.setFrameBufferDepthStencilTexture(this);
  66660. };
  66661. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66662. if (size.ratio) {
  66663. this._sizeRatio = size.ratio;
  66664. this._size = {
  66665. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66666. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66667. };
  66668. }
  66669. else {
  66670. this._size = size;
  66671. }
  66672. };
  66673. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66674. get: function () {
  66675. return this._samples;
  66676. },
  66677. set: function (value) {
  66678. if (this._samples === value) {
  66679. return;
  66680. }
  66681. var scene = this.getScene();
  66682. if (!scene) {
  66683. return;
  66684. }
  66685. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66686. },
  66687. enumerable: true,
  66688. configurable: true
  66689. });
  66690. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66691. this._currentRefreshId = -1;
  66692. };
  66693. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66694. get: function () {
  66695. return this._refreshRate;
  66696. },
  66697. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66698. set: function (value) {
  66699. this._refreshRate = value;
  66700. this.resetRefreshCounter();
  66701. },
  66702. enumerable: true,
  66703. configurable: true
  66704. });
  66705. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66706. if (!this._postProcessManager) {
  66707. var scene = this.getScene();
  66708. if (!scene) {
  66709. return;
  66710. }
  66711. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66712. this._postProcesses = new Array();
  66713. }
  66714. this._postProcesses.push(postProcess);
  66715. this._postProcesses[0].autoClear = false;
  66716. };
  66717. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66718. if (!this._postProcesses) {
  66719. return;
  66720. }
  66721. if (dispose) {
  66722. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66723. var postProcess = _a[_i];
  66724. postProcess.dispose();
  66725. }
  66726. }
  66727. this._postProcesses = [];
  66728. };
  66729. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66730. if (!this._postProcesses) {
  66731. return;
  66732. }
  66733. var index = this._postProcesses.indexOf(postProcess);
  66734. if (index === -1) {
  66735. return;
  66736. }
  66737. this._postProcesses.splice(index, 1);
  66738. if (this._postProcesses.length > 0) {
  66739. this._postProcesses[0].autoClear = false;
  66740. }
  66741. };
  66742. /** @hidden */
  66743. RenderTargetTexture.prototype._shouldRender = function () {
  66744. if (this._currentRefreshId === -1) { // At least render once
  66745. this._currentRefreshId = 1;
  66746. return true;
  66747. }
  66748. if (this.refreshRate === this._currentRefreshId) {
  66749. this._currentRefreshId = 1;
  66750. return true;
  66751. }
  66752. this._currentRefreshId++;
  66753. return false;
  66754. };
  66755. RenderTargetTexture.prototype.getRenderSize = function () {
  66756. if (this._size.width) {
  66757. return this._size.width;
  66758. }
  66759. return this._size;
  66760. };
  66761. RenderTargetTexture.prototype.getRenderWidth = function () {
  66762. if (this._size.width) {
  66763. return this._size.width;
  66764. }
  66765. return this._size;
  66766. };
  66767. RenderTargetTexture.prototype.getRenderHeight = function () {
  66768. if (this._size.width) {
  66769. return this._size.height;
  66770. }
  66771. return this._size;
  66772. };
  66773. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66774. get: function () {
  66775. return true;
  66776. },
  66777. enumerable: true,
  66778. configurable: true
  66779. });
  66780. RenderTargetTexture.prototype.scale = function (ratio) {
  66781. var newSize = this.getRenderSize() * ratio;
  66782. this.resize(newSize);
  66783. };
  66784. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66785. if (this.isCube) {
  66786. return this._textureMatrix;
  66787. }
  66788. return _super.prototype.getReflectionTextureMatrix.call(this);
  66789. };
  66790. RenderTargetTexture.prototype.resize = function (size) {
  66791. this.releaseInternalTexture();
  66792. var scene = this.getScene();
  66793. if (!scene) {
  66794. return;
  66795. }
  66796. this._processSizeParameter(size);
  66797. if (this.isCube) {
  66798. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66799. }
  66800. else {
  66801. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66802. }
  66803. };
  66804. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66805. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66806. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66807. var scene = this.getScene();
  66808. if (!scene) {
  66809. return;
  66810. }
  66811. var engine = scene.getEngine();
  66812. if (this.useCameraPostProcesses !== undefined) {
  66813. useCameraPostProcess = this.useCameraPostProcesses;
  66814. }
  66815. if (this._waitingRenderList) {
  66816. this.renderList = [];
  66817. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66818. var id = this._waitingRenderList[index];
  66819. var mesh_1 = scene.getMeshByID(id);
  66820. if (mesh_1) {
  66821. this.renderList.push(mesh_1);
  66822. }
  66823. }
  66824. delete this._waitingRenderList;
  66825. }
  66826. // Is predicate defined?
  66827. if (this.renderListPredicate) {
  66828. if (this.renderList) {
  66829. this.renderList.splice(0); // Clear previous renderList
  66830. }
  66831. else {
  66832. this.renderList = [];
  66833. }
  66834. var scene = this.getScene();
  66835. if (!scene) {
  66836. return;
  66837. }
  66838. var sceneMeshes = scene.meshes;
  66839. for (var index = 0; index < sceneMeshes.length; index++) {
  66840. var mesh = sceneMeshes[index];
  66841. if (this.renderListPredicate(mesh)) {
  66842. this.renderList.push(mesh);
  66843. }
  66844. }
  66845. }
  66846. this.onBeforeBindObservable.notifyObservers(this);
  66847. // Set custom projection.
  66848. // Needs to be before binding to prevent changing the aspect ratio.
  66849. var camera;
  66850. if (this.activeCamera) {
  66851. camera = this.activeCamera;
  66852. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66853. if (this.activeCamera !== scene.activeCamera) {
  66854. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66855. }
  66856. }
  66857. else {
  66858. camera = scene.activeCamera;
  66859. if (camera) {
  66860. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66861. }
  66862. }
  66863. // Prepare renderingManager
  66864. this._renderingManager.reset();
  66865. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  66866. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  66867. var sceneRenderId = scene.getRenderId();
  66868. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  66869. var mesh = currentRenderList[meshIndex];
  66870. if (mesh) {
  66871. if (!mesh.isReady(this.refreshRate === 0)) {
  66872. this.resetRefreshCounter();
  66873. continue;
  66874. }
  66875. mesh._preActivateForIntermediateRendering(sceneRenderId);
  66876. var isMasked = void 0;
  66877. if (!this.renderList && camera) {
  66878. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  66879. }
  66880. else {
  66881. isMasked = false;
  66882. }
  66883. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  66884. mesh._activate(sceneRenderId);
  66885. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  66886. var subMesh = mesh.subMeshes[subIndex];
  66887. scene._activeIndices.addCount(subMesh.indexCount, false);
  66888. this._renderingManager.dispatch(subMesh, mesh);
  66889. }
  66890. }
  66891. }
  66892. }
  66893. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  66894. var particleSystem = scene.particleSystems[particleIndex];
  66895. var emitter = particleSystem.emitter;
  66896. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  66897. continue;
  66898. }
  66899. if (currentRenderList.indexOf(emitter) >= 0) {
  66900. this._renderingManager.dispatchParticles(particleSystem);
  66901. }
  66902. }
  66903. if (this.isCube) {
  66904. for (var face = 0; face < 6; face++) {
  66905. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66906. scene.incrementRenderId();
  66907. scene.resetCachedMaterial();
  66908. }
  66909. }
  66910. else {
  66911. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66912. }
  66913. this.onAfterUnbindObservable.notifyObservers(this);
  66914. if (scene.activeCamera) {
  66915. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  66916. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  66917. }
  66918. engine.setViewport(scene.activeCamera.viewport);
  66919. }
  66920. scene.resetCachedMaterial();
  66921. };
  66922. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  66923. var minimum = 128;
  66924. var x = renderDimension * scale;
  66925. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66926. // Ensure we don't exceed the render dimension (while staying POT)
  66927. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66928. };
  66929. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66930. var _this = this;
  66931. if (!this._texture) {
  66932. return;
  66933. }
  66934. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66935. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66936. });
  66937. };
  66938. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66939. var scene = this.getScene();
  66940. if (!scene) {
  66941. return;
  66942. }
  66943. var engine = scene.getEngine();
  66944. if (!this._texture) {
  66945. return;
  66946. }
  66947. // Bind
  66948. if (this._postProcessManager) {
  66949. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66950. }
  66951. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66952. if (this._texture) {
  66953. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66954. }
  66955. }
  66956. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66957. // Clear
  66958. if (this.onClearObservable.hasObservers()) {
  66959. this.onClearObservable.notifyObservers(engine);
  66960. }
  66961. else {
  66962. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66963. }
  66964. if (!this._doNotChangeAspectRatio) {
  66965. scene.updateTransformMatrix(true);
  66966. }
  66967. // Render
  66968. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66969. if (this._postProcessManager) {
  66970. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66971. }
  66972. else if (useCameraPostProcess) {
  66973. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66974. }
  66975. if (!this._doNotChangeAspectRatio) {
  66976. scene.updateTransformMatrix(true);
  66977. }
  66978. // Dump ?
  66979. if (dumpForDebug) {
  66980. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66981. }
  66982. // Unbind
  66983. if (!this.isCube || faceIndex === 5) {
  66984. if (this.isCube) {
  66985. if (faceIndex === 5) {
  66986. engine.generateMipMapsForCubemap(this._texture);
  66987. }
  66988. }
  66989. this.unbindFrameBuffer(engine, faceIndex);
  66990. }
  66991. else {
  66992. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66993. }
  66994. };
  66995. /**
  66996. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66997. * This allowed control for front to back rendering or reversly depending of the special needs.
  66998. *
  66999. * @param renderingGroupId The rendering group id corresponding to its index
  67000. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67001. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67002. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67003. */
  67004. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67005. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67006. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67007. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67008. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67009. };
  67010. /**
  67011. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67012. *
  67013. * @param renderingGroupId The rendering group id corresponding to its index
  67014. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67015. */
  67016. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67017. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67018. this._renderingManager._useSceneAutoClearSetup = false;
  67019. };
  67020. RenderTargetTexture.prototype.clone = function () {
  67021. var textureSize = this.getSize();
  67022. 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);
  67023. // Base texture
  67024. newTexture.hasAlpha = this.hasAlpha;
  67025. newTexture.level = this.level;
  67026. // RenderTarget Texture
  67027. newTexture.coordinatesMode = this.coordinatesMode;
  67028. if (this.renderList) {
  67029. newTexture.renderList = this.renderList.slice(0);
  67030. }
  67031. return newTexture;
  67032. };
  67033. RenderTargetTexture.prototype.serialize = function () {
  67034. if (!this.name) {
  67035. return null;
  67036. }
  67037. var serializationObject = _super.prototype.serialize.call(this);
  67038. serializationObject.renderTargetSize = this.getRenderSize();
  67039. serializationObject.renderList = [];
  67040. if (this.renderList) {
  67041. for (var index = 0; index < this.renderList.length; index++) {
  67042. serializationObject.renderList.push(this.renderList[index].id);
  67043. }
  67044. }
  67045. return serializationObject;
  67046. };
  67047. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67048. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67049. var objBuffer = this.getInternalTexture();
  67050. var scene = this.getScene();
  67051. if (objBuffer && scene) {
  67052. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67053. }
  67054. };
  67055. RenderTargetTexture.prototype.dispose = function () {
  67056. if (this._postProcessManager) {
  67057. this._postProcessManager.dispose();
  67058. this._postProcessManager = null;
  67059. }
  67060. this.clearPostProcesses(true);
  67061. if (this._resizeObserver) {
  67062. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67063. this._resizeObserver = null;
  67064. }
  67065. this.renderList = null;
  67066. // Remove from custom render targets
  67067. var scene = this.getScene();
  67068. if (!scene) {
  67069. return;
  67070. }
  67071. var index = scene.customRenderTargets.indexOf(this);
  67072. if (index >= 0) {
  67073. scene.customRenderTargets.splice(index, 1);
  67074. }
  67075. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67076. var camera = _a[_i];
  67077. index = camera.customRenderTargets.indexOf(this);
  67078. if (index >= 0) {
  67079. camera.customRenderTargets.splice(index, 1);
  67080. }
  67081. }
  67082. _super.prototype.dispose.call(this);
  67083. };
  67084. /** @hidden */
  67085. RenderTargetTexture.prototype._rebuild = function () {
  67086. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67087. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67088. }
  67089. if (this._postProcessManager) {
  67090. this._postProcessManager._rebuild();
  67091. }
  67092. };
  67093. /**
  67094. * Clear the info related to rendering groups preventing retention point in material dispose.
  67095. */
  67096. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67097. if (this._renderingManager) {
  67098. this._renderingManager.freeRenderingGroups();
  67099. }
  67100. };
  67101. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67102. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67103. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67104. return RenderTargetTexture;
  67105. }(BABYLON.Texture));
  67106. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67107. })(BABYLON || (BABYLON = {}));
  67108. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67109. var BABYLON;
  67110. (function (BABYLON) {
  67111. ;
  67112. var MultiRenderTarget = /** @class */ (function (_super) {
  67113. __extends(MultiRenderTarget, _super);
  67114. function MultiRenderTarget(name, size, count, scene, options) {
  67115. var _this = this;
  67116. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67117. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67118. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67119. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67120. _this._engine = scene.getEngine();
  67121. if (!_this.isSupported) {
  67122. _this.dispose();
  67123. return;
  67124. }
  67125. var types = [];
  67126. var samplingModes = [];
  67127. for (var i = 0; i < count; i++) {
  67128. if (options && options.types && options.types[i] !== undefined) {
  67129. types.push(options.types[i]);
  67130. }
  67131. else {
  67132. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67133. }
  67134. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67135. samplingModes.push(options.samplingModes[i]);
  67136. }
  67137. else {
  67138. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67139. }
  67140. }
  67141. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  67142. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  67143. _this._size = size;
  67144. _this._multiRenderTargetOptions = {
  67145. samplingModes: samplingModes,
  67146. generateMipMaps: generateMipMaps,
  67147. generateDepthBuffer: generateDepthBuffer,
  67148. generateStencilBuffer: generateStencilBuffer,
  67149. generateDepthTexture: generateDepthTexture,
  67150. types: types,
  67151. textureCount: count
  67152. };
  67153. _this._createInternalTextures();
  67154. _this._createTextures();
  67155. return _this;
  67156. }
  67157. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  67158. get: function () {
  67159. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  67160. },
  67161. enumerable: true,
  67162. configurable: true
  67163. });
  67164. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  67165. get: function () {
  67166. return this._textures;
  67167. },
  67168. enumerable: true,
  67169. configurable: true
  67170. });
  67171. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  67172. get: function () {
  67173. return this._textures[this._textures.length - 1];
  67174. },
  67175. enumerable: true,
  67176. configurable: true
  67177. });
  67178. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  67179. set: function (wrap) {
  67180. if (this._textures) {
  67181. for (var i = 0; i < this._textures.length; i++) {
  67182. this._textures[i].wrapU = wrap;
  67183. }
  67184. }
  67185. },
  67186. enumerable: true,
  67187. configurable: true
  67188. });
  67189. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  67190. set: function (wrap) {
  67191. if (this._textures) {
  67192. for (var i = 0; i < this._textures.length; i++) {
  67193. this._textures[i].wrapV = wrap;
  67194. }
  67195. }
  67196. },
  67197. enumerable: true,
  67198. configurable: true
  67199. });
  67200. /** @hidden */
  67201. MultiRenderTarget.prototype._rebuild = function () {
  67202. this.releaseInternalTextures();
  67203. this._createInternalTextures();
  67204. for (var i = 0; i < this._internalTextures.length; i++) {
  67205. var texture = this._textures[i];
  67206. texture._texture = this._internalTextures[i];
  67207. }
  67208. // Keeps references to frame buffer and stencil/depth buffer
  67209. this._texture = this._internalTextures[0];
  67210. };
  67211. MultiRenderTarget.prototype._createInternalTextures = function () {
  67212. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  67213. };
  67214. MultiRenderTarget.prototype._createTextures = function () {
  67215. this._textures = [];
  67216. for (var i = 0; i < this._internalTextures.length; i++) {
  67217. var texture = new BABYLON.Texture(null, this.getScene());
  67218. texture._texture = this._internalTextures[i];
  67219. this._textures.push(texture);
  67220. }
  67221. // Keeps references to frame buffer and stencil/depth buffer
  67222. this._texture = this._internalTextures[0];
  67223. };
  67224. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  67225. get: function () {
  67226. return this._samples;
  67227. },
  67228. set: function (value) {
  67229. if (this._samples === value) {
  67230. return;
  67231. }
  67232. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  67233. },
  67234. enumerable: true,
  67235. configurable: true
  67236. });
  67237. MultiRenderTarget.prototype.resize = function (size) {
  67238. this.releaseInternalTextures();
  67239. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  67240. this._createInternalTextures();
  67241. };
  67242. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67243. var _this = this;
  67244. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67245. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67246. });
  67247. };
  67248. MultiRenderTarget.prototype.dispose = function () {
  67249. this.releaseInternalTextures();
  67250. _super.prototype.dispose.call(this);
  67251. };
  67252. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67253. if (!this._internalTextures) {
  67254. return;
  67255. }
  67256. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67257. if (this._internalTextures[i] !== undefined) {
  67258. this._internalTextures[i].dispose();
  67259. this._internalTextures.splice(i, 1);
  67260. }
  67261. }
  67262. };
  67263. return MultiRenderTarget;
  67264. }(BABYLON.RenderTargetTexture));
  67265. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67266. })(BABYLON || (BABYLON = {}));
  67267. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67268. var BABYLON;
  67269. (function (BABYLON) {
  67270. var MirrorTexture = /** @class */ (function (_super) {
  67271. __extends(MirrorTexture, _super);
  67272. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67273. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67274. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67275. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67276. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67277. _this.scene = scene;
  67278. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67279. _this._transformMatrix = BABYLON.Matrix.Zero();
  67280. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67281. _this._adaptiveBlurKernel = 0;
  67282. _this._blurKernelX = 0;
  67283. _this._blurKernelY = 0;
  67284. _this._blurRatio = 1.0;
  67285. _this.ignoreCameraViewport = true;
  67286. _this._updateGammaSpace();
  67287. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67288. _this._updateGammaSpace;
  67289. });
  67290. _this.onBeforeRenderObservable.add(function () {
  67291. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67292. _this._savedViewMatrix = scene.getViewMatrix();
  67293. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67294. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67295. scene.clipPlane = _this.mirrorPlane;
  67296. scene.getEngine().cullBackFaces = false;
  67297. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67298. });
  67299. _this.onAfterRenderObservable.add(function () {
  67300. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67301. scene.getEngine().cullBackFaces = true;
  67302. scene._mirroredCameraPosition = null;
  67303. delete scene.clipPlane;
  67304. });
  67305. return _this;
  67306. }
  67307. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67308. get: function () {
  67309. return this._blurRatio;
  67310. },
  67311. set: function (value) {
  67312. if (this._blurRatio === value) {
  67313. return;
  67314. }
  67315. this._blurRatio = value;
  67316. this._preparePostProcesses();
  67317. },
  67318. enumerable: true,
  67319. configurable: true
  67320. });
  67321. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67322. set: function (value) {
  67323. this._adaptiveBlurKernel = value;
  67324. this._autoComputeBlurKernel();
  67325. },
  67326. enumerable: true,
  67327. configurable: true
  67328. });
  67329. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67330. set: function (value) {
  67331. this.blurKernelX = value;
  67332. this.blurKernelY = value;
  67333. },
  67334. enumerable: true,
  67335. configurable: true
  67336. });
  67337. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67338. get: function () {
  67339. return this._blurKernelX;
  67340. },
  67341. set: function (value) {
  67342. if (this._blurKernelX === value) {
  67343. return;
  67344. }
  67345. this._blurKernelX = value;
  67346. this._preparePostProcesses();
  67347. },
  67348. enumerable: true,
  67349. configurable: true
  67350. });
  67351. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67352. get: function () {
  67353. return this._blurKernelY;
  67354. },
  67355. set: function (value) {
  67356. if (this._blurKernelY === value) {
  67357. return;
  67358. }
  67359. this._blurKernelY = value;
  67360. this._preparePostProcesses();
  67361. },
  67362. enumerable: true,
  67363. configurable: true
  67364. });
  67365. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67366. var engine = this.getScene().getEngine();
  67367. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67368. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67369. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67370. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67371. };
  67372. MirrorTexture.prototype._onRatioRescale = function () {
  67373. if (this._sizeRatio) {
  67374. this.resize(this._initialSizeParameter);
  67375. if (!this._adaptiveBlurKernel) {
  67376. this._preparePostProcesses();
  67377. }
  67378. }
  67379. if (this._adaptiveBlurKernel) {
  67380. this._autoComputeBlurKernel();
  67381. }
  67382. };
  67383. MirrorTexture.prototype._updateGammaSpace = function () {
  67384. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67385. };
  67386. MirrorTexture.prototype._preparePostProcesses = function () {
  67387. this.clearPostProcesses(true);
  67388. if (this._blurKernelX && this._blurKernelY) {
  67389. var engine = this.getScene().getEngine();
  67390. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67391. 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);
  67392. this._blurX.autoClear = false;
  67393. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67394. this._blurX.inputTexture = this._texture;
  67395. }
  67396. else {
  67397. this._blurX.alwaysForcePOT = true;
  67398. }
  67399. 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);
  67400. this._blurY.autoClear = false;
  67401. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67402. this.addPostProcess(this._blurX);
  67403. this.addPostProcess(this._blurY);
  67404. }
  67405. else {
  67406. if (this._blurY) {
  67407. this.removePostProcess(this._blurY);
  67408. this._blurY.dispose();
  67409. this._blurY = null;
  67410. }
  67411. if (this._blurX) {
  67412. this.removePostProcess(this._blurX);
  67413. this._blurX.dispose();
  67414. this._blurX = null;
  67415. }
  67416. }
  67417. };
  67418. MirrorTexture.prototype.clone = function () {
  67419. var scene = this.getScene();
  67420. if (!scene) {
  67421. return this;
  67422. }
  67423. var textureSize = this.getSize();
  67424. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67425. // Base texture
  67426. newTexture.hasAlpha = this.hasAlpha;
  67427. newTexture.level = this.level;
  67428. // Mirror Texture
  67429. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67430. if (this.renderList) {
  67431. newTexture.renderList = this.renderList.slice(0);
  67432. }
  67433. return newTexture;
  67434. };
  67435. MirrorTexture.prototype.serialize = function () {
  67436. if (!this.name) {
  67437. return null;
  67438. }
  67439. var serializationObject = _super.prototype.serialize.call(this);
  67440. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67441. return serializationObject;
  67442. };
  67443. MirrorTexture.prototype.dispose = function () {
  67444. _super.prototype.dispose.call(this);
  67445. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67446. };
  67447. return MirrorTexture;
  67448. }(BABYLON.RenderTargetTexture));
  67449. BABYLON.MirrorTexture = MirrorTexture;
  67450. })(BABYLON || (BABYLON = {}));
  67451. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67452. var BABYLON;
  67453. (function (BABYLON) {
  67454. /**
  67455. * Creates a refraction texture used by refraction channel of the standard material.
  67456. * @param name the texture name
  67457. * @param size size of the underlying texture
  67458. * @param scene root scene
  67459. */
  67460. var RefractionTexture = /** @class */ (function (_super) {
  67461. __extends(RefractionTexture, _super);
  67462. function RefractionTexture(name, size, scene, generateMipMaps) {
  67463. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67464. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67465. _this.depth = 2.0;
  67466. _this.onBeforeRenderObservable.add(function () {
  67467. scene.clipPlane = _this.refractionPlane;
  67468. });
  67469. _this.onAfterRenderObservable.add(function () {
  67470. delete scene.clipPlane;
  67471. });
  67472. return _this;
  67473. }
  67474. RefractionTexture.prototype.clone = function () {
  67475. var scene = this.getScene();
  67476. if (!scene) {
  67477. return this;
  67478. }
  67479. var textureSize = this.getSize();
  67480. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67481. // Base texture
  67482. newTexture.hasAlpha = this.hasAlpha;
  67483. newTexture.level = this.level;
  67484. // Refraction Texture
  67485. newTexture.refractionPlane = this.refractionPlane.clone();
  67486. if (this.renderList) {
  67487. newTexture.renderList = this.renderList.slice(0);
  67488. }
  67489. newTexture.depth = this.depth;
  67490. return newTexture;
  67491. };
  67492. RefractionTexture.prototype.serialize = function () {
  67493. if (!this.name) {
  67494. return null;
  67495. }
  67496. var serializationObject = _super.prototype.serialize.call(this);
  67497. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67498. serializationObject.depth = this.depth;
  67499. return serializationObject;
  67500. };
  67501. return RefractionTexture;
  67502. }(BABYLON.RenderTargetTexture));
  67503. BABYLON.RefractionTexture = RefractionTexture;
  67504. })(BABYLON || (BABYLON = {}));
  67505. //# sourceMappingURL=babylon.refractionTexture.js.map
  67506. var BABYLON;
  67507. (function (BABYLON) {
  67508. /**
  67509. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67510. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67511. */
  67512. var DynamicTexture = /** @class */ (function (_super) {
  67513. __extends(DynamicTexture, _super);
  67514. /**
  67515. * Creates a {BABYLON.DynamicTexture}
  67516. * @param name defines the name of the texture
  67517. * @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
  67518. * @param scene defines the scene where you want the texture
  67519. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67520. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67521. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67522. */
  67523. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67524. if (scene === void 0) { scene = null; }
  67525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67526. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67527. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67528. _this.name = name;
  67529. _this._engine = _this.getScene().getEngine();
  67530. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67531. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67532. _this._generateMipMaps = generateMipMaps;
  67533. if (options.getContext) {
  67534. _this._canvas = options;
  67535. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67536. }
  67537. else {
  67538. _this._canvas = document.createElement("canvas");
  67539. if (options.width || options.width === 0) {
  67540. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67541. }
  67542. else {
  67543. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67544. }
  67545. }
  67546. var textureSize = _this.getSize();
  67547. _this._canvas.width = textureSize.width;
  67548. _this._canvas.height = textureSize.height;
  67549. _this._context = _this._canvas.getContext("2d");
  67550. return _this;
  67551. }
  67552. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67553. /**
  67554. * Gets the current state of canRescale
  67555. */
  67556. get: function () {
  67557. return true;
  67558. },
  67559. enumerable: true,
  67560. configurable: true
  67561. });
  67562. DynamicTexture.prototype._recreate = function (textureSize) {
  67563. this._canvas.width = textureSize.width;
  67564. this._canvas.height = textureSize.height;
  67565. this.releaseInternalTexture();
  67566. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67567. };
  67568. /**
  67569. * Scales the texture
  67570. * @param ratio the scale factor to apply to both width and height
  67571. */
  67572. DynamicTexture.prototype.scale = function (ratio) {
  67573. var textureSize = this.getSize();
  67574. textureSize.width *= ratio;
  67575. textureSize.height *= ratio;
  67576. this._recreate(textureSize);
  67577. };
  67578. /**
  67579. * Resizes the texture
  67580. * @param width the new width
  67581. * @param height the new height
  67582. */
  67583. DynamicTexture.prototype.scaleTo = function (width, height) {
  67584. var textureSize = this.getSize();
  67585. textureSize.width = width;
  67586. textureSize.height = height;
  67587. this._recreate(textureSize);
  67588. };
  67589. /**
  67590. * Gets the context of the canvas used by the texture
  67591. * @returns the canvas context of the dynamic texture
  67592. */
  67593. DynamicTexture.prototype.getContext = function () {
  67594. return this._context;
  67595. };
  67596. /**
  67597. * Clears the texture
  67598. */
  67599. DynamicTexture.prototype.clear = function () {
  67600. var size = this.getSize();
  67601. this._context.fillRect(0, 0, size.width, size.height);
  67602. };
  67603. /**
  67604. * Updates the texture
  67605. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67606. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67607. */
  67608. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67609. if (premulAlpha === void 0) { premulAlpha = false; }
  67610. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67611. };
  67612. /**
  67613. * Draws text onto the texture
  67614. * @param text defines the text to be drawn
  67615. * @param x defines the placement of the text from the left
  67616. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67617. * @param font defines the font to be used with font-style, font-size, font-name
  67618. * @param color defines the color used for the text
  67619. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67620. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67621. * @param update defines whether texture is immediately update (default is true)
  67622. */
  67623. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67624. if (update === void 0) { update = true; }
  67625. var size = this.getSize();
  67626. if (clearColor) {
  67627. this._context.fillStyle = clearColor;
  67628. this._context.fillRect(0, 0, size.width, size.height);
  67629. }
  67630. this._context.font = font;
  67631. if (x === null || x === undefined) {
  67632. var textSize = this._context.measureText(text);
  67633. x = (size.width - textSize.width) / 2;
  67634. }
  67635. if (y === null || y === undefined) {
  67636. var fontSize = parseInt((font.replace(/\D/g, '')));
  67637. y = (size.height / 2) + (fontSize / 3.65);
  67638. }
  67639. this._context.fillStyle = color;
  67640. this._context.fillText(text, x, y);
  67641. if (update) {
  67642. this.update(invertY);
  67643. }
  67644. };
  67645. /**
  67646. * Clones the texture
  67647. * @returns the clone of the texture.
  67648. */
  67649. DynamicTexture.prototype.clone = function () {
  67650. var scene = this.getScene();
  67651. if (!scene) {
  67652. return this;
  67653. }
  67654. var textureSize = this.getSize();
  67655. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67656. // Base texture
  67657. newTexture.hasAlpha = this.hasAlpha;
  67658. newTexture.level = this.level;
  67659. // Dynamic Texture
  67660. newTexture.wrapU = this.wrapU;
  67661. newTexture.wrapV = this.wrapV;
  67662. return newTexture;
  67663. };
  67664. /**
  67665. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67666. * @returns a serialized dynamic texture object
  67667. */
  67668. DynamicTexture.prototype.serialize = function () {
  67669. var scene = this.getScene();
  67670. if (scene && !scene.isReady()) {
  67671. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67672. }
  67673. var serializationObject = _super.prototype.serialize.call(this);
  67674. serializationObject.base64String = this._canvas.toDataURL();
  67675. serializationObject.invertY = this._invertY;
  67676. serializationObject.samplingMode = this.samplingMode;
  67677. return serializationObject;
  67678. };
  67679. /** @hidden */
  67680. DynamicTexture.prototype._rebuild = function () {
  67681. this.update();
  67682. };
  67683. return DynamicTexture;
  67684. }(BABYLON.Texture));
  67685. BABYLON.DynamicTexture = DynamicTexture;
  67686. })(BABYLON || (BABYLON = {}));
  67687. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67688. var BABYLON;
  67689. (function (BABYLON) {
  67690. var VideoTexture = /** @class */ (function (_super) {
  67691. __extends(VideoTexture, _super);
  67692. /**
  67693. * Creates a video texture.
  67694. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67695. * @param {string | null} name optional name, will detect from video source, if not defined
  67696. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67697. * @param {BABYLON.Scene} scene is obviously the current scene.
  67698. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67699. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67700. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67701. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67702. */
  67703. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67704. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67705. if (invertY === void 0) { invertY = false; }
  67706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67707. if (settings === void 0) { settings = {
  67708. autoPlay: true,
  67709. loop: true,
  67710. autoUpdateTexture: true,
  67711. }; }
  67712. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67713. _this._onUserActionRequestedObservable = null;
  67714. _this._stillImageCaptured = false;
  67715. _this._poster = false;
  67716. _this._createInternalTexture = function () {
  67717. if (_this._texture != null) {
  67718. if (_this._poster) {
  67719. _this._texture.dispose();
  67720. _this._poster = false;
  67721. }
  67722. else {
  67723. return;
  67724. }
  67725. }
  67726. if (!_this._engine.needPOTTextures ||
  67727. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67728. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67729. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67730. }
  67731. else {
  67732. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67733. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67734. _this._generateMipMaps = false;
  67735. }
  67736. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67737. if (!_this.video.autoplay) {
  67738. var oldHandler_1 = _this.video.onplaying;
  67739. var error_1 = false;
  67740. _this.video.onplaying = function () {
  67741. _this.video.onplaying = oldHandler_1;
  67742. _this._texture.isReady = true;
  67743. _this._updateInternalTexture();
  67744. if (!error_1) {
  67745. _this.video.pause();
  67746. }
  67747. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67748. _this.onLoadObservable.notifyObservers(_this);
  67749. }
  67750. };
  67751. var playing = _this.video.play();
  67752. if (playing) {
  67753. playing.then(function () {
  67754. // Everything is good.
  67755. })
  67756. .catch(function () {
  67757. error_1 = true;
  67758. // On Chrome for instance, new policies might prevent playing without user interaction.
  67759. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67760. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67761. }
  67762. });
  67763. }
  67764. else {
  67765. _this.video.onplaying = oldHandler_1;
  67766. _this._texture.isReady = true;
  67767. _this._updateInternalTexture();
  67768. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67769. _this.onLoadObservable.notifyObservers(_this);
  67770. }
  67771. }
  67772. }
  67773. else {
  67774. _this._texture.isReady = true;
  67775. _this._updateInternalTexture();
  67776. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67777. _this.onLoadObservable.notifyObservers(_this);
  67778. }
  67779. }
  67780. };
  67781. _this.reset = function () {
  67782. if (_this._texture == null) {
  67783. return;
  67784. }
  67785. if (!_this._poster) {
  67786. _this._texture.dispose();
  67787. _this._texture = null;
  67788. }
  67789. };
  67790. _this._updateInternalTexture = function (e) {
  67791. if (_this._texture == null || !_this._texture.isReady) {
  67792. return;
  67793. }
  67794. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67795. return;
  67796. }
  67797. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67798. };
  67799. _this._engine = _this.getScene().getEngine();
  67800. _this._generateMipMaps = generateMipMaps;
  67801. _this._samplingMode = samplingMode;
  67802. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67803. _this.name = name || _this._getName(src);
  67804. _this.video = _this._getVideo(src);
  67805. if (settings.poster) {
  67806. _this.video.poster = settings.poster;
  67807. }
  67808. if (settings.autoPlay !== undefined) {
  67809. _this.video.autoplay = settings.autoPlay;
  67810. }
  67811. if (settings.loop !== undefined) {
  67812. _this.video.loop = settings.loop;
  67813. }
  67814. _this.video.setAttribute("playsinline", "");
  67815. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67816. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67817. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67818. _this.video.addEventListener("emptied", _this.reset);
  67819. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67820. _this._createInternalTexture();
  67821. }
  67822. if (settings.poster) {
  67823. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67824. _this._poster = true;
  67825. }
  67826. return _this;
  67827. }
  67828. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67829. get: function () {
  67830. if (!this._onUserActionRequestedObservable) {
  67831. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67832. }
  67833. return this._onUserActionRequestedObservable;
  67834. },
  67835. enumerable: true,
  67836. configurable: true
  67837. });
  67838. VideoTexture.prototype._getName = function (src) {
  67839. if (src instanceof HTMLVideoElement) {
  67840. return src.currentSrc;
  67841. }
  67842. if (typeof src === "object") {
  67843. return src.toString();
  67844. }
  67845. return src;
  67846. };
  67847. ;
  67848. VideoTexture.prototype._getVideo = function (src) {
  67849. if (src instanceof HTMLVideoElement) {
  67850. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67851. return src;
  67852. }
  67853. var video = document.createElement("video");
  67854. if (typeof src === "string") {
  67855. BABYLON.Tools.SetCorsBehavior(src, video);
  67856. video.src = src;
  67857. }
  67858. else {
  67859. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67860. src.forEach(function (url) {
  67861. var source = document.createElement("source");
  67862. source.src = url;
  67863. video.appendChild(source);
  67864. });
  67865. }
  67866. return video;
  67867. };
  67868. ;
  67869. /**
  67870. * @hidden Internal method to initiate `update`.
  67871. */
  67872. VideoTexture.prototype._rebuild = function () {
  67873. this.update();
  67874. };
  67875. /**
  67876. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  67877. */
  67878. VideoTexture.prototype.update = function () {
  67879. if (!this.autoUpdateTexture) {
  67880. // Expecting user to call `updateTexture` manually
  67881. return;
  67882. }
  67883. this.updateTexture(true);
  67884. };
  67885. /**
  67886. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  67887. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  67888. */
  67889. VideoTexture.prototype.updateTexture = function (isVisible) {
  67890. if (!isVisible) {
  67891. return;
  67892. }
  67893. if (this.video.paused && this._stillImageCaptured) {
  67894. return;
  67895. }
  67896. this._stillImageCaptured = true;
  67897. this._updateInternalTexture();
  67898. };
  67899. /**
  67900. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  67901. * @param url New url.
  67902. */
  67903. VideoTexture.prototype.updateURL = function (url) {
  67904. this.video.src = url;
  67905. };
  67906. VideoTexture.prototype.dispose = function () {
  67907. _super.prototype.dispose.call(this);
  67908. if (this._onUserActionRequestedObservable) {
  67909. this._onUserActionRequestedObservable.clear();
  67910. this._onUserActionRequestedObservable = null;
  67911. }
  67912. this.video.removeEventListener("canplay", this._createInternalTexture);
  67913. this.video.removeEventListener("paused", this._updateInternalTexture);
  67914. this.video.removeEventListener("seeked", this._updateInternalTexture);
  67915. this.video.removeEventListener("emptied", this.reset);
  67916. this.video.pause();
  67917. };
  67918. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  67919. var video = document.createElement("video");
  67920. video.setAttribute('autoplay', '');
  67921. video.setAttribute('muted', '');
  67922. video.setAttribute('playsinline', '');
  67923. var constraintsDeviceId;
  67924. if (constraints && constraints.deviceId) {
  67925. constraintsDeviceId = {
  67926. exact: constraints.deviceId,
  67927. };
  67928. }
  67929. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67930. if (navigator.mediaDevices) {
  67931. navigator.mediaDevices.getUserMedia({ video: constraints })
  67932. .then(function (stream) {
  67933. if (video.mozSrcObject !== undefined) {
  67934. // hack for Firefox < 19
  67935. video.mozSrcObject = stream;
  67936. }
  67937. else {
  67938. video.srcObject = stream;
  67939. }
  67940. var onPlaying = function () {
  67941. if (onReady) {
  67942. onReady(new VideoTexture("video", video, scene, true, true));
  67943. }
  67944. video.removeEventListener("playing", onPlaying);
  67945. };
  67946. video.addEventListener("playing", onPlaying);
  67947. video.play();
  67948. })
  67949. .catch(function (err) {
  67950. BABYLON.Tools.Error(err.name);
  67951. });
  67952. }
  67953. else {
  67954. navigator.getUserMedia =
  67955. navigator.getUserMedia ||
  67956. navigator.webkitGetUserMedia ||
  67957. navigator.mozGetUserMedia ||
  67958. navigator.msGetUserMedia;
  67959. if (navigator.getUserMedia) {
  67960. navigator.getUserMedia({
  67961. video: {
  67962. deviceId: constraintsDeviceId,
  67963. width: {
  67964. min: (constraints && constraints.minWidth) || 256,
  67965. max: (constraints && constraints.maxWidth) || 640,
  67966. },
  67967. height: {
  67968. min: (constraints && constraints.minHeight) || 256,
  67969. max: (constraints && constraints.maxHeight) || 480,
  67970. },
  67971. },
  67972. }, function (stream) {
  67973. if (video.mozSrcObject !== undefined) {
  67974. // hack for Firefox < 19
  67975. video.mozSrcObject = stream;
  67976. }
  67977. else {
  67978. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67979. }
  67980. video.play();
  67981. if (onReady) {
  67982. onReady(new VideoTexture("video", video, scene, true, true));
  67983. }
  67984. }, function (e) {
  67985. BABYLON.Tools.Error(e.name);
  67986. });
  67987. }
  67988. }
  67989. };
  67990. return VideoTexture;
  67991. }(BABYLON.Texture));
  67992. BABYLON.VideoTexture = VideoTexture;
  67993. })(BABYLON || (BABYLON = {}));
  67994. //# sourceMappingURL=babylon.videoTexture.js.map
  67995. var BABYLON;
  67996. (function (BABYLON) {
  67997. var RawTexture = /** @class */ (function (_super) {
  67998. __extends(RawTexture, _super);
  67999. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68000. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68001. if (invertY === void 0) { invertY = false; }
  68002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68003. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68004. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68005. _this.format = format;
  68006. _this._engine = scene.getEngine();
  68007. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68008. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68009. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68010. return _this;
  68011. }
  68012. RawTexture.prototype.update = function (data) {
  68013. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68014. };
  68015. // Statics
  68016. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68017. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68018. if (invertY === void 0) { invertY = false; }
  68019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68020. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68021. };
  68022. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68023. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68024. if (invertY === void 0) { invertY = false; }
  68025. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68026. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68027. };
  68028. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68029. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68030. if (invertY === void 0) { invertY = false; }
  68031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68032. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68033. };
  68034. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68035. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68036. if (invertY === void 0) { invertY = false; }
  68037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68038. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68039. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68040. };
  68041. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68042. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68043. if (invertY === void 0) { invertY = false; }
  68044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68045. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68046. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68047. };
  68048. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68049. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68050. if (invertY === void 0) { invertY = false; }
  68051. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68052. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68053. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68054. };
  68055. return RawTexture;
  68056. }(BABYLON.Texture));
  68057. BABYLON.RawTexture = RawTexture;
  68058. })(BABYLON || (BABYLON = {}));
  68059. //# sourceMappingURL=babylon.rawTexture.js.map
  68060. var BABYLON;
  68061. (function (BABYLON) {
  68062. /**
  68063. * Class used to store 3D textures containing user data
  68064. */
  68065. var RawTexture3D = /** @class */ (function (_super) {
  68066. __extends(RawTexture3D, _super);
  68067. /**
  68068. * Create a new RawTexture3D
  68069. * @param data defines the data of the texture
  68070. * @param width defines the width of the texture
  68071. * @param height defines the height of the texture
  68072. * @param depth defines the depth of the texture
  68073. * @param format defines the texture format to use
  68074. * @param scene defines the hosting scene
  68075. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68076. * @param invertY defines if texture must be stored with Y axis inverted
  68077. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68078. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68079. */
  68080. function RawTexture3D(data, width, height, depth,
  68081. /** Gets or sets the texture format to use */
  68082. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68084. if (invertY === void 0) { invertY = false; }
  68085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68086. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68087. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68088. _this.format = format;
  68089. _this._engine = scene.getEngine();
  68090. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68091. _this.is3D = true;
  68092. return _this;
  68093. }
  68094. /**
  68095. * Update the texture with new data
  68096. * @param data defines the data to store in the texture
  68097. */
  68098. RawTexture3D.prototype.update = function (data) {
  68099. if (!this._texture) {
  68100. return;
  68101. }
  68102. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68103. };
  68104. return RawTexture3D;
  68105. }(BABYLON.Texture));
  68106. BABYLON.RawTexture3D = RawTexture3D;
  68107. })(BABYLON || (BABYLON = {}));
  68108. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68109. var BABYLON;
  68110. (function (BABYLON) {
  68111. /**
  68112. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68113. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68114. */
  68115. var PostProcessManager = /** @class */ (function () {
  68116. /**
  68117. * Creates a new instance PostProcess
  68118. * @param scene The scene that the post process is associated with.
  68119. */
  68120. function PostProcessManager(scene) {
  68121. this._vertexBuffers = {};
  68122. this._scene = scene;
  68123. }
  68124. PostProcessManager.prototype._prepareBuffers = function () {
  68125. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68126. return;
  68127. }
  68128. // VBO
  68129. var vertices = [];
  68130. vertices.push(1, 1);
  68131. vertices.push(-1, 1);
  68132. vertices.push(-1, -1);
  68133. vertices.push(1, -1);
  68134. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68135. this._buildIndexBuffer();
  68136. };
  68137. PostProcessManager.prototype._buildIndexBuffer = function () {
  68138. // Indices
  68139. var indices = [];
  68140. indices.push(0);
  68141. indices.push(1);
  68142. indices.push(2);
  68143. indices.push(0);
  68144. indices.push(2);
  68145. indices.push(3);
  68146. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  68147. };
  68148. /**
  68149. * Rebuilds the vertex buffers of the manager.
  68150. * @hidden
  68151. */
  68152. PostProcessManager.prototype._rebuild = function () {
  68153. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68154. if (!vb) {
  68155. return;
  68156. }
  68157. vb._rebuild();
  68158. this._buildIndexBuffer();
  68159. };
  68160. // Methods
  68161. /**
  68162. * Prepares a frame to be run through a post process.
  68163. * @param sourceTexture The input texture to the post procesess. (default: null)
  68164. * @param postProcesses An array of post processes to be run. (default: null)
  68165. * @returns True if the post processes were able to be run.
  68166. * @hidden
  68167. */
  68168. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  68169. if (sourceTexture === void 0) { sourceTexture = null; }
  68170. if (postProcesses === void 0) { postProcesses = null; }
  68171. var camera = this._scene.activeCamera;
  68172. if (!camera) {
  68173. return false;
  68174. }
  68175. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68176. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68177. return false;
  68178. }
  68179. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  68180. return true;
  68181. };
  68182. /**
  68183. * Manually render a set of post processes to a texture.
  68184. * @param postProcesses An array of post processes to be run.
  68185. * @param targetTexture The target texture to render to.
  68186. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  68187. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  68188. * @param lodLevel defines which lod of the texture to render to
  68189. */
  68190. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  68191. if (targetTexture === void 0) { targetTexture = null; }
  68192. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68193. if (faceIndex === void 0) { faceIndex = 0; }
  68194. if (lodLevel === void 0) { lodLevel = 0; }
  68195. var engine = this._scene.getEngine();
  68196. for (var index = 0; index < postProcesses.length; index++) {
  68197. if (index < postProcesses.length - 1) {
  68198. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  68199. }
  68200. else {
  68201. if (targetTexture) {
  68202. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  68203. }
  68204. else {
  68205. engine.restoreDefaultFramebuffer();
  68206. }
  68207. }
  68208. var pp = postProcesses[index];
  68209. var effect = pp.apply();
  68210. if (effect) {
  68211. pp.onBeforeRenderObservable.notifyObservers(effect);
  68212. // VBOs
  68213. this._prepareBuffers();
  68214. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68215. // Draw order
  68216. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68217. pp.onAfterRenderObservable.notifyObservers(effect);
  68218. }
  68219. }
  68220. // Restore depth buffer
  68221. engine.setDepthBuffer(true);
  68222. engine.setDepthWrite(true);
  68223. };
  68224. /**
  68225. * Finalize the result of the output of the postprocesses.
  68226. * @param doNotPresent If true the result will not be displayed to the screen.
  68227. * @param targetTexture The target texture to render to.
  68228. * @param faceIndex The index of the face to bind the target texture to.
  68229. * @param postProcesses The array of post processes to render.
  68230. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  68231. * @hidden
  68232. */
  68233. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  68234. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  68235. var camera = this._scene.activeCamera;
  68236. if (!camera) {
  68237. return;
  68238. }
  68239. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  68240. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  68241. return;
  68242. }
  68243. var engine = this._scene.getEngine();
  68244. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68245. var pp = postProcesses[index];
  68246. if (index < len - 1) {
  68247. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68248. }
  68249. else {
  68250. if (targetTexture) {
  68251. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68252. pp._outputTexture = targetTexture;
  68253. }
  68254. else {
  68255. engine.restoreDefaultFramebuffer();
  68256. pp._outputTexture = null;
  68257. }
  68258. }
  68259. if (doNotPresent) {
  68260. break;
  68261. }
  68262. var effect = pp.apply();
  68263. if (effect) {
  68264. pp.onBeforeRenderObservable.notifyObservers(effect);
  68265. // VBOs
  68266. this._prepareBuffers();
  68267. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68268. // Draw order
  68269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68270. pp.onAfterRenderObservable.notifyObservers(effect);
  68271. }
  68272. }
  68273. // Restore states
  68274. engine.setDepthBuffer(true);
  68275. engine.setDepthWrite(true);
  68276. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68277. };
  68278. /**
  68279. * Disposes of the post process manager.
  68280. */
  68281. PostProcessManager.prototype.dispose = function () {
  68282. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68283. if (buffer) {
  68284. buffer.dispose();
  68285. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68286. }
  68287. if (this._indexBuffer) {
  68288. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68289. this._indexBuffer = null;
  68290. }
  68291. };
  68292. return PostProcessManager;
  68293. }());
  68294. BABYLON.PostProcessManager = PostProcessManager;
  68295. })(BABYLON || (BABYLON = {}));
  68296. //# sourceMappingURL=babylon.postProcessManager.js.map
  68297. var BABYLON;
  68298. (function (BABYLON) {
  68299. /**
  68300. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68301. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68302. */
  68303. var PostProcess = /** @class */ (function () {
  68304. /**
  68305. * Creates a new instance PostProcess
  68306. * @param name The name of the PostProcess.
  68307. * @param fragmentUrl The url of the fragment shader to be used.
  68308. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68309. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68310. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68311. * @param camera The camera to apply the render pass to.
  68312. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68313. * @param engine The engine which the post process will be applied. (default: current engine)
  68314. * @param reusable If the post process can be reused on the same frame. (default: false)
  68315. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68316. * @param textureType Type of textures used when performing the post process. (default: 0)
  68317. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68318. * @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
  68319. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68320. */
  68321. function PostProcess(
  68322. /** Name of the PostProcess. */
  68323. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68325. if (defines === void 0) { defines = null; }
  68326. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68327. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68328. if (blockCompilation === void 0) { blockCompilation = false; }
  68329. this.name = name;
  68330. /**
  68331. * Width of the texture to apply the post process on
  68332. */
  68333. this.width = -1;
  68334. /**
  68335. * Height of the texture to apply the post process on
  68336. */
  68337. this.height = -1;
  68338. /**
  68339. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68340. * @hidden
  68341. */
  68342. this._outputTexture = null;
  68343. /**
  68344. * If the buffer needs to be cleared before applying the post process. (default: true)
  68345. * Should be set to false if shader will overwrite all previous pixels.
  68346. */
  68347. this.autoClear = true;
  68348. /**
  68349. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68350. */
  68351. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68352. /**
  68353. * Animations to be used for the post processing
  68354. */
  68355. this.animations = new Array();
  68356. /**
  68357. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68358. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68359. */
  68360. this.enablePixelPerfectMode = false;
  68361. /**
  68362. * Force the postprocess to be applied without taking in account viewport
  68363. */
  68364. this.forceFullscreenViewport = true;
  68365. /**
  68366. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68367. *
  68368. * | Value | Type | Description |
  68369. * | ----- | ----------------------------------- | ----------- |
  68370. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68371. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68372. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68373. *
  68374. */
  68375. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68376. /**
  68377. * Force textures to be a power of two (default: false)
  68378. */
  68379. this.alwaysForcePOT = false;
  68380. this._samples = 1;
  68381. /**
  68382. * Modify the scale of the post process to be the same as the viewport (default: false)
  68383. */
  68384. this.adaptScaleToCurrentViewport = false;
  68385. this._reusable = false;
  68386. /**
  68387. * Smart array of input and output textures for the post process.
  68388. * @hidden
  68389. */
  68390. this._textures = new BABYLON.SmartArray(2);
  68391. /**
  68392. * The index in _textures that corresponds to the output texture.
  68393. * @hidden
  68394. */
  68395. this._currentRenderTextureInd = 0;
  68396. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68397. this._texelSize = BABYLON.Vector2.Zero();
  68398. // Events
  68399. /**
  68400. * An event triggered when the postprocess is activated.
  68401. */
  68402. this.onActivateObservable = new BABYLON.Observable();
  68403. /**
  68404. * An event triggered when the postprocess changes its size.
  68405. */
  68406. this.onSizeChangedObservable = new BABYLON.Observable();
  68407. /**
  68408. * An event triggered when the postprocess applies its effect.
  68409. */
  68410. this.onApplyObservable = new BABYLON.Observable();
  68411. /**
  68412. * An event triggered before rendering the postprocess
  68413. */
  68414. this.onBeforeRenderObservable = new BABYLON.Observable();
  68415. /**
  68416. * An event triggered after rendering the postprocess
  68417. */
  68418. this.onAfterRenderObservable = new BABYLON.Observable();
  68419. if (camera != null) {
  68420. this._camera = camera;
  68421. this._scene = camera.getScene();
  68422. camera.attachPostProcess(this);
  68423. this._engine = this._scene.getEngine();
  68424. this._scene.postProcesses.push(this);
  68425. }
  68426. else if (engine) {
  68427. this._engine = engine;
  68428. this._engine.postProcesses.push(this);
  68429. }
  68430. this._options = options;
  68431. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68432. this._reusable = reusable || false;
  68433. this._textureType = textureType;
  68434. this._samplers = samplers || [];
  68435. this._samplers.push("textureSampler");
  68436. this._fragmentUrl = fragmentUrl;
  68437. this._vertexUrl = vertexUrl;
  68438. this._parameters = parameters || [];
  68439. this._parameters.push("scale");
  68440. this._indexParameters = indexParameters;
  68441. if (!blockCompilation) {
  68442. this.updateEffect(defines);
  68443. }
  68444. }
  68445. Object.defineProperty(PostProcess.prototype, "samples", {
  68446. /**
  68447. * Number of sample textures (default: 1)
  68448. */
  68449. get: function () {
  68450. return this._samples;
  68451. },
  68452. set: function (n) {
  68453. var _this = this;
  68454. this._samples = n;
  68455. this._textures.forEach(function (texture) {
  68456. if (texture.samples !== _this._samples) {
  68457. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  68458. }
  68459. });
  68460. },
  68461. enumerable: true,
  68462. configurable: true
  68463. });
  68464. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68465. /**
  68466. * A function that is added to the onActivateObservable
  68467. */
  68468. set: function (callback) {
  68469. if (this._onActivateObserver) {
  68470. this.onActivateObservable.remove(this._onActivateObserver);
  68471. }
  68472. if (callback) {
  68473. this._onActivateObserver = this.onActivateObservable.add(callback);
  68474. }
  68475. },
  68476. enumerable: true,
  68477. configurable: true
  68478. });
  68479. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68480. /**
  68481. * A function that is added to the onSizeChangedObservable
  68482. */
  68483. set: function (callback) {
  68484. if (this._onSizeChangedObserver) {
  68485. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68486. }
  68487. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68488. },
  68489. enumerable: true,
  68490. configurable: true
  68491. });
  68492. Object.defineProperty(PostProcess.prototype, "onApply", {
  68493. /**
  68494. * A function that is added to the onApplyObservable
  68495. */
  68496. set: function (callback) {
  68497. if (this._onApplyObserver) {
  68498. this.onApplyObservable.remove(this._onApplyObserver);
  68499. }
  68500. this._onApplyObserver = this.onApplyObservable.add(callback);
  68501. },
  68502. enumerable: true,
  68503. configurable: true
  68504. });
  68505. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68506. /**
  68507. * A function that is added to the onBeforeRenderObservable
  68508. */
  68509. set: function (callback) {
  68510. if (this._onBeforeRenderObserver) {
  68511. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68512. }
  68513. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68514. },
  68515. enumerable: true,
  68516. configurable: true
  68517. });
  68518. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68519. /**
  68520. * A function that is added to the onAfterRenderObservable
  68521. */
  68522. set: function (callback) {
  68523. if (this._onAfterRenderObserver) {
  68524. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68525. }
  68526. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68527. },
  68528. enumerable: true,
  68529. configurable: true
  68530. });
  68531. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68532. /**
  68533. * 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
  68534. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68535. */
  68536. get: function () {
  68537. return this._textures.data[this._currentRenderTextureInd];
  68538. },
  68539. set: function (value) {
  68540. this._forcedOutputTexture = value;
  68541. },
  68542. enumerable: true,
  68543. configurable: true
  68544. });
  68545. /**
  68546. * Gets the camera which post process is applied to.
  68547. * @returns The camera the post process is applied to.
  68548. */
  68549. PostProcess.prototype.getCamera = function () {
  68550. return this._camera;
  68551. };
  68552. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68553. /**
  68554. * Gets the texel size of the postprocess.
  68555. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68556. */
  68557. get: function () {
  68558. if (this._shareOutputWithPostProcess) {
  68559. return this._shareOutputWithPostProcess.texelSize;
  68560. }
  68561. if (this._forcedOutputTexture) {
  68562. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68563. }
  68564. return this._texelSize;
  68565. },
  68566. enumerable: true,
  68567. configurable: true
  68568. });
  68569. /**
  68570. * Gets the engine which this post process belongs to.
  68571. * @returns The engine the post process was enabled with.
  68572. */
  68573. PostProcess.prototype.getEngine = function () {
  68574. return this._engine;
  68575. };
  68576. /**
  68577. * The effect that is created when initializing the post process.
  68578. * @returns The created effect corrisponding the the postprocess.
  68579. */
  68580. PostProcess.prototype.getEffect = function () {
  68581. return this._effect;
  68582. };
  68583. /**
  68584. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68585. * @param postProcess The post process to share the output with.
  68586. * @returns This post process.
  68587. */
  68588. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68589. this._disposeTextures();
  68590. this._shareOutputWithPostProcess = postProcess;
  68591. return this;
  68592. };
  68593. /**
  68594. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68595. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68596. */
  68597. PostProcess.prototype.useOwnOutput = function () {
  68598. if (this._textures.length == 0) {
  68599. this._textures = new BABYLON.SmartArray(2);
  68600. }
  68601. this._shareOutputWithPostProcess = null;
  68602. };
  68603. /**
  68604. * Updates the effect with the current post process compile time values and recompiles the shader.
  68605. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68606. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68607. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68608. * @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
  68609. * @param onCompiled Called when the shader has been compiled.
  68610. * @param onError Called if there is an error when compiling a shader.
  68611. */
  68612. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68613. if (defines === void 0) { defines = null; }
  68614. if (uniforms === void 0) { uniforms = null; }
  68615. if (samplers === void 0) { samplers = null; }
  68616. 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);
  68617. };
  68618. /**
  68619. * The post process is reusable if it can be used multiple times within one frame.
  68620. * @returns If the post process is reusable
  68621. */
  68622. PostProcess.prototype.isReusable = function () {
  68623. return this._reusable;
  68624. };
  68625. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68626. PostProcess.prototype.markTextureDirty = function () {
  68627. this.width = -1;
  68628. };
  68629. /**
  68630. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68631. * 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.
  68632. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68633. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68634. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68635. * @returns The target texture that was bound to be written to.
  68636. */
  68637. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68638. var _this = this;
  68639. if (sourceTexture === void 0) { sourceTexture = null; }
  68640. camera = camera || this._camera;
  68641. var scene = camera.getScene();
  68642. var engine = scene.getEngine();
  68643. var maxSize = engine.getCaps().maxTextureSize;
  68644. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68645. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68646. // 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
  68647. var webVRCamera = camera.parent;
  68648. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68649. requiredWidth /= 2;
  68650. }
  68651. var desiredWidth = (this._options.width || requiredWidth);
  68652. var desiredHeight = this._options.height || requiredHeight;
  68653. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68654. if (this.adaptScaleToCurrentViewport) {
  68655. var currentViewport = engine.currentViewport;
  68656. if (currentViewport) {
  68657. desiredWidth *= currentViewport.width;
  68658. desiredHeight *= currentViewport.height;
  68659. }
  68660. }
  68661. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68662. if (!this._options.width) {
  68663. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68664. }
  68665. if (!this._options.height) {
  68666. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68667. }
  68668. }
  68669. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68670. if (this._textures.length > 0) {
  68671. for (var i = 0; i < this._textures.length; i++) {
  68672. this._engine._releaseTexture(this._textures.data[i]);
  68673. }
  68674. this._textures.reset();
  68675. }
  68676. this.width = desiredWidth;
  68677. this.height = desiredHeight;
  68678. var textureSize = { width: this.width, height: this.height };
  68679. var textureOptions = {
  68680. generateMipMaps: false,
  68681. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68682. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68683. samplingMode: this.renderTargetSamplingMode,
  68684. type: this._textureType
  68685. };
  68686. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68687. if (this._reusable) {
  68688. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68689. }
  68690. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68691. this.onSizeChangedObservable.notifyObservers(this);
  68692. }
  68693. this._textures.forEach(function (texture) {
  68694. if (texture.samples !== _this.samples) {
  68695. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68696. }
  68697. });
  68698. }
  68699. var target;
  68700. if (this._shareOutputWithPostProcess) {
  68701. target = this._shareOutputWithPostProcess.inputTexture;
  68702. }
  68703. else if (this._forcedOutputTexture) {
  68704. target = this._forcedOutputTexture;
  68705. this.width = this._forcedOutputTexture.width;
  68706. this.height = this._forcedOutputTexture.height;
  68707. }
  68708. else {
  68709. target = this.inputTexture;
  68710. }
  68711. // Bind the input of this post process to be used as the output of the previous post process.
  68712. if (this.enablePixelPerfectMode) {
  68713. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68714. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68715. }
  68716. else {
  68717. this._scaleRatio.copyFromFloats(1, 1);
  68718. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68719. }
  68720. this.onActivateObservable.notifyObservers(camera);
  68721. // Clear
  68722. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68723. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68724. }
  68725. if (this._reusable) {
  68726. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68727. }
  68728. return target;
  68729. };
  68730. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68731. /**
  68732. * If the post process is supported.
  68733. */
  68734. get: function () {
  68735. return this._effect.isSupported;
  68736. },
  68737. enumerable: true,
  68738. configurable: true
  68739. });
  68740. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68741. /**
  68742. * The aspect ratio of the output texture.
  68743. */
  68744. get: function () {
  68745. if (this._shareOutputWithPostProcess) {
  68746. return this._shareOutputWithPostProcess.aspectRatio;
  68747. }
  68748. if (this._forcedOutputTexture) {
  68749. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68750. }
  68751. return this.width / this.height;
  68752. },
  68753. enumerable: true,
  68754. configurable: true
  68755. });
  68756. /**
  68757. * Get a value indicating if the post-process is ready to be used
  68758. * @returns true if the post-process is ready (shader is compiled)
  68759. */
  68760. PostProcess.prototype.isReady = function () {
  68761. return this._effect && this._effect.isReady();
  68762. };
  68763. /**
  68764. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68765. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68766. */
  68767. PostProcess.prototype.apply = function () {
  68768. // Check
  68769. if (!this._effect || !this._effect.isReady())
  68770. return null;
  68771. // States
  68772. this._engine.enableEffect(this._effect);
  68773. this._engine.setState(false);
  68774. this._engine.setDepthBuffer(false);
  68775. this._engine.setDepthWrite(false);
  68776. // Alpha
  68777. this._engine.setAlphaMode(this.alphaMode);
  68778. if (this.alphaConstants) {
  68779. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68780. }
  68781. // Bind the output texture of the preivous post process as the input to this post process.
  68782. var source;
  68783. if (this._shareOutputWithPostProcess) {
  68784. source = this._shareOutputWithPostProcess.inputTexture;
  68785. }
  68786. else if (this._forcedOutputTexture) {
  68787. source = this._forcedOutputTexture;
  68788. }
  68789. else {
  68790. source = this.inputTexture;
  68791. }
  68792. this._effect._bindTexture("textureSampler", source);
  68793. // Parameters
  68794. this._effect.setVector2("scale", this._scaleRatio);
  68795. this.onApplyObservable.notifyObservers(this._effect);
  68796. return this._effect;
  68797. };
  68798. PostProcess.prototype._disposeTextures = function () {
  68799. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68800. return;
  68801. }
  68802. if (this._textures.length > 0) {
  68803. for (var i = 0; i < this._textures.length; i++) {
  68804. this._engine._releaseTexture(this._textures.data[i]);
  68805. }
  68806. }
  68807. this._textures.dispose();
  68808. };
  68809. /**
  68810. * Disposes the post process.
  68811. * @param camera The camera to dispose the post process on.
  68812. */
  68813. PostProcess.prototype.dispose = function (camera) {
  68814. camera = camera || this._camera;
  68815. this._disposeTextures();
  68816. if (this._scene) {
  68817. var index_1 = this._scene.postProcesses.indexOf(this);
  68818. if (index_1 !== -1) {
  68819. this._scene.postProcesses.splice(index_1, 1);
  68820. }
  68821. }
  68822. else {
  68823. var index_2 = this._engine.postProcesses.indexOf(this);
  68824. if (index_2 !== -1) {
  68825. this._engine.postProcesses.splice(index_2, 1);
  68826. }
  68827. }
  68828. if (!camera) {
  68829. return;
  68830. }
  68831. camera.detachPostProcess(this);
  68832. var index = camera._postProcesses.indexOf(this);
  68833. if (index === 0 && camera._postProcesses.length > 0) {
  68834. var firstPostProcess = this._camera._getFirstPostProcess();
  68835. if (firstPostProcess) {
  68836. firstPostProcess.markTextureDirty();
  68837. }
  68838. }
  68839. this.onActivateObservable.clear();
  68840. this.onAfterRenderObservable.clear();
  68841. this.onApplyObservable.clear();
  68842. this.onBeforeRenderObservable.clear();
  68843. this.onSizeChangedObservable.clear();
  68844. };
  68845. return PostProcess;
  68846. }());
  68847. BABYLON.PostProcess = PostProcess;
  68848. })(BABYLON || (BABYLON = {}));
  68849. //# sourceMappingURL=babylon.postProcess.js.map
  68850. var BABYLON;
  68851. (function (BABYLON) {
  68852. var PassPostProcess = /** @class */ (function (_super) {
  68853. __extends(PassPostProcess, _super);
  68854. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68855. if (camera === void 0) { camera = null; }
  68856. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68857. if (blockCompilation === void 0) { blockCompilation = false; }
  68858. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68859. }
  68860. return PassPostProcess;
  68861. }(BABYLON.PostProcess));
  68862. BABYLON.PassPostProcess = PassPostProcess;
  68863. })(BABYLON || (BABYLON = {}));
  68864. //# sourceMappingURL=babylon.passPostProcess.js.map
  68865. var __assign = (this && this.__assign) || function () {
  68866. __assign = Object.assign || function(t) {
  68867. for (var s, i = 1, n = arguments.length; i < n; i++) {
  68868. s = arguments[i];
  68869. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  68870. t[p] = s[p];
  68871. }
  68872. return t;
  68873. };
  68874. return __assign.apply(this, arguments);
  68875. };
  68876. var BABYLON;
  68877. (function (BABYLON) {
  68878. /**
  68879. * Default implementation IShadowGenerator.
  68880. * This is the main object responsible of generating shadows in the framework.
  68881. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  68882. */
  68883. var ShadowGenerator = /** @class */ (function () {
  68884. /**
  68885. * Creates a ShadowGenerator object.
  68886. * A ShadowGenerator is the required tool to use the shadows.
  68887. * Each light casting shadows needs to use its own ShadowGenerator.
  68888. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  68889. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  68890. * @param light The light object generating the shadows.
  68891. * @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.
  68892. */
  68893. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  68894. this._bias = 0.00005;
  68895. this._normalBias = 0;
  68896. this._blurBoxOffset = 1;
  68897. this._blurScale = 2;
  68898. this._blurKernel = 1;
  68899. this._useKernelBlur = false;
  68900. this._filter = ShadowGenerator.FILTER_NONE;
  68901. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  68902. this._contactHardeningLightSizeUVRatio = 0.1;
  68903. this._darkness = 0;
  68904. this._transparencyShadow = false;
  68905. /**
  68906. * Controls the extent to which the shadows fade out at the edge of the frustum
  68907. * Used only by directionals and spots
  68908. */
  68909. this.frustumEdgeFalloff = 0;
  68910. /**
  68911. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  68912. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  68913. * It might on the other hand introduce peter panning.
  68914. */
  68915. this.forceBackFacesOnly = false;
  68916. this._lightDirection = BABYLON.Vector3.Zero();
  68917. this._viewMatrix = BABYLON.Matrix.Zero();
  68918. this._projectionMatrix = BABYLON.Matrix.Zero();
  68919. this._transformMatrix = BABYLON.Matrix.Zero();
  68920. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68921. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68922. this._currentFaceIndex = 0;
  68923. this._currentFaceIndexCache = 0;
  68924. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  68925. this._mapSize = mapSize;
  68926. this._light = light;
  68927. this._scene = light.getScene();
  68928. light._shadowGenerator = this;
  68929. // Texture type fallback from float to int if not supported.
  68930. var caps = this._scene.getEngine().getCaps();
  68931. if (!useFullFloatFirst) {
  68932. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68933. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68934. }
  68935. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68936. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68937. }
  68938. else {
  68939. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68940. }
  68941. }
  68942. else {
  68943. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68944. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68945. }
  68946. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68947. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68948. }
  68949. else {
  68950. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68951. }
  68952. }
  68953. this._initializeGenerator();
  68954. this._applyFilterValues();
  68955. }
  68956. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68957. /**
  68958. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68959. */
  68960. get: function () {
  68961. return this._bias;
  68962. },
  68963. /**
  68964. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68965. */
  68966. set: function (bias) {
  68967. this._bias = bias;
  68968. },
  68969. enumerable: true,
  68970. configurable: true
  68971. });
  68972. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68973. /**
  68974. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68975. */
  68976. get: function () {
  68977. return this._normalBias;
  68978. },
  68979. /**
  68980. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68981. */
  68982. set: function (normalBias) {
  68983. this._normalBias = normalBias;
  68984. },
  68985. enumerable: true,
  68986. configurable: true
  68987. });
  68988. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68989. /**
  68990. * Gets the blur box offset: offset applied during the blur pass.
  68991. * Only usefull if useKernelBlur = false
  68992. */
  68993. get: function () {
  68994. return this._blurBoxOffset;
  68995. },
  68996. /**
  68997. * Sets the blur box offset: offset applied during the blur pass.
  68998. * Only usefull if useKernelBlur = false
  68999. */
  69000. set: function (value) {
  69001. if (this._blurBoxOffset === value) {
  69002. return;
  69003. }
  69004. this._blurBoxOffset = value;
  69005. this._disposeBlurPostProcesses();
  69006. },
  69007. enumerable: true,
  69008. configurable: true
  69009. });
  69010. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69011. /**
  69012. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69013. * 2 means half of the size.
  69014. */
  69015. get: function () {
  69016. return this._blurScale;
  69017. },
  69018. /**
  69019. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69020. * 2 means half of the size.
  69021. */
  69022. set: function (value) {
  69023. if (this._blurScale === value) {
  69024. return;
  69025. }
  69026. this._blurScale = value;
  69027. this._disposeBlurPostProcesses();
  69028. },
  69029. enumerable: true,
  69030. configurable: true
  69031. });
  69032. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69033. /**
  69034. * Gets the blur kernel: kernel size of the blur pass.
  69035. * Only usefull if useKernelBlur = true
  69036. */
  69037. get: function () {
  69038. return this._blurKernel;
  69039. },
  69040. /**
  69041. * Sets the blur kernel: kernel size of the blur pass.
  69042. * Only usefull if useKernelBlur = true
  69043. */
  69044. set: function (value) {
  69045. if (this._blurKernel === value) {
  69046. return;
  69047. }
  69048. this._blurKernel = value;
  69049. this._disposeBlurPostProcesses();
  69050. },
  69051. enumerable: true,
  69052. configurable: true
  69053. });
  69054. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69055. /**
  69056. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69057. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69058. */
  69059. get: function () {
  69060. return this._useKernelBlur;
  69061. },
  69062. /**
  69063. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69064. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69065. */
  69066. set: function (value) {
  69067. if (this._useKernelBlur === value) {
  69068. return;
  69069. }
  69070. this._useKernelBlur = value;
  69071. this._disposeBlurPostProcesses();
  69072. },
  69073. enumerable: true,
  69074. configurable: true
  69075. });
  69076. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69077. /**
  69078. * Gets the depth scale used in ESM mode.
  69079. */
  69080. get: function () {
  69081. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69082. },
  69083. /**
  69084. * Sets the depth scale used in ESM mode.
  69085. * This can override the scale stored on the light.
  69086. */
  69087. set: function (value) {
  69088. this._depthScale = value;
  69089. },
  69090. enumerable: true,
  69091. configurable: true
  69092. });
  69093. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69094. /**
  69095. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69096. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69097. */
  69098. get: function () {
  69099. return this._filter;
  69100. },
  69101. /**
  69102. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69103. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69104. */
  69105. set: function (value) {
  69106. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69107. if (this._light.needCube()) {
  69108. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69109. this.useExponentialShadowMap = true;
  69110. return;
  69111. }
  69112. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69113. this.useCloseExponentialShadowMap = true;
  69114. return;
  69115. }
  69116. // PCF on cubemap would also be expensive
  69117. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69118. this.usePoissonSampling = true;
  69119. return;
  69120. }
  69121. }
  69122. // Weblg1 fallback for PCF.
  69123. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69124. if (this._scene.getEngine().webGLVersion === 1) {
  69125. this.usePoissonSampling = true;
  69126. return;
  69127. }
  69128. }
  69129. if (this._filter === value) {
  69130. return;
  69131. }
  69132. this._filter = value;
  69133. this._disposeBlurPostProcesses();
  69134. this._applyFilterValues();
  69135. this._light._markMeshesAsLightDirty();
  69136. },
  69137. enumerable: true,
  69138. configurable: true
  69139. });
  69140. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  69141. /**
  69142. * Gets if the current filter is set to Poisson Sampling.
  69143. */
  69144. get: function () {
  69145. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  69146. },
  69147. /**
  69148. * Sets the current filter to Poisson Sampling.
  69149. */
  69150. set: function (value) {
  69151. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  69152. return;
  69153. }
  69154. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  69155. },
  69156. enumerable: true,
  69157. configurable: true
  69158. });
  69159. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  69160. /**
  69161. * Gets if the current filter is set to VSM.
  69162. * DEPRECATED. Should use useExponentialShadowMap instead.
  69163. */
  69164. get: function () {
  69165. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69166. return this.useExponentialShadowMap;
  69167. },
  69168. /**
  69169. * Sets the current filter is to VSM.
  69170. * DEPRECATED. Should use useExponentialShadowMap instead.
  69171. */
  69172. set: function (value) {
  69173. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  69174. this.useExponentialShadowMap = value;
  69175. },
  69176. enumerable: true,
  69177. configurable: true
  69178. });
  69179. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  69180. /**
  69181. * Gets if the current filter is set to blurred VSM.
  69182. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69183. */
  69184. get: function () {
  69185. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69186. return this.useBlurExponentialShadowMap;
  69187. },
  69188. /**
  69189. * Sets the current filter is to blurred VSM.
  69190. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  69191. */
  69192. set: function (value) {
  69193. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  69194. this.useBlurExponentialShadowMap = value;
  69195. },
  69196. enumerable: true,
  69197. configurable: true
  69198. });
  69199. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  69200. /**
  69201. * Gets if the current filter is set to ESM.
  69202. */
  69203. get: function () {
  69204. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  69205. },
  69206. /**
  69207. * Sets the current filter is to ESM.
  69208. */
  69209. set: function (value) {
  69210. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  69211. return;
  69212. }
  69213. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69214. },
  69215. enumerable: true,
  69216. configurable: true
  69217. });
  69218. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  69219. /**
  69220. * Gets if the current filter is set to filtered ESM.
  69221. */
  69222. get: function () {
  69223. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  69224. },
  69225. /**
  69226. * Gets if the current filter is set to filtered ESM.
  69227. */
  69228. set: function (value) {
  69229. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69230. return;
  69231. }
  69232. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69233. },
  69234. enumerable: true,
  69235. configurable: true
  69236. });
  69237. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  69238. /**
  69239. * Gets if the current filter is set to "close ESM" (using the inverse of the
  69240. * exponential to prevent steep falloff artifacts).
  69241. */
  69242. get: function () {
  69243. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  69244. },
  69245. /**
  69246. * Sets the current filter to "close ESM" (using the inverse of the
  69247. * exponential to prevent steep falloff artifacts).
  69248. */
  69249. set: function (value) {
  69250. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  69251. return;
  69252. }
  69253. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69254. },
  69255. enumerable: true,
  69256. configurable: true
  69257. });
  69258. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  69259. /**
  69260. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69261. * exponential to prevent steep falloff artifacts).
  69262. */
  69263. get: function () {
  69264. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69265. },
  69266. /**
  69267. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69268. * exponential to prevent steep falloff artifacts).
  69269. */
  69270. set: function (value) {
  69271. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69272. return;
  69273. }
  69274. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69275. },
  69276. enumerable: true,
  69277. configurable: true
  69278. });
  69279. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69280. /**
  69281. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69282. */
  69283. get: function () {
  69284. return this.filter === ShadowGenerator.FILTER_PCF;
  69285. },
  69286. /**
  69287. * Sets the current filter to "PCF" (percentage closer filtering).
  69288. */
  69289. set: function (value) {
  69290. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69291. return;
  69292. }
  69293. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69294. },
  69295. enumerable: true,
  69296. configurable: true
  69297. });
  69298. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69299. /**
  69300. * Gets the PCF or PCSS Quality.
  69301. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69302. */
  69303. get: function () {
  69304. return this._filteringQuality;
  69305. },
  69306. /**
  69307. * Sets the PCF or PCSS Quality.
  69308. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69309. */
  69310. set: function (filteringQuality) {
  69311. this._filteringQuality = filteringQuality;
  69312. },
  69313. enumerable: true,
  69314. configurable: true
  69315. });
  69316. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69317. /**
  69318. * Gets if the current filter is set to "PCSS" (contact hardening).
  69319. */
  69320. get: function () {
  69321. return this.filter === ShadowGenerator.FILTER_PCSS;
  69322. },
  69323. /**
  69324. * Sets the current filter to "PCSS" (contact hardening).
  69325. */
  69326. set: function (value) {
  69327. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69328. return;
  69329. }
  69330. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69331. },
  69332. enumerable: true,
  69333. configurable: true
  69334. });
  69335. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69336. /**
  69337. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69338. * Using a ratio helps keeping shape stability independently of the map size.
  69339. *
  69340. * It does not account for the light projection as it was having too much
  69341. * instability during the light setup or during light position changes.
  69342. *
  69343. * Only valid if useContactHardeningShadow is true.
  69344. */
  69345. get: function () {
  69346. return this._contactHardeningLightSizeUVRatio;
  69347. },
  69348. /**
  69349. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69350. * Using a ratio helps keeping shape stability independently of the map size.
  69351. *
  69352. * It does not account for the light projection as it was having too much
  69353. * instability during the light setup or during light position changes.
  69354. *
  69355. * Only valid if useContactHardeningShadow is true.
  69356. */
  69357. set: function (contactHardeningLightSizeUVRatio) {
  69358. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69359. },
  69360. enumerable: true,
  69361. configurable: true
  69362. });
  69363. /**
  69364. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69365. * 0 means strongest and 1 would means no shadow.
  69366. * @returns the darkness.
  69367. */
  69368. ShadowGenerator.prototype.getDarkness = function () {
  69369. return this._darkness;
  69370. };
  69371. /**
  69372. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69373. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69374. * @returns the shadow generator allowing fluent coding.
  69375. */
  69376. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69377. if (darkness >= 1.0)
  69378. this._darkness = 1.0;
  69379. else if (darkness <= 0.0)
  69380. this._darkness = 0.0;
  69381. else
  69382. this._darkness = darkness;
  69383. return this;
  69384. };
  69385. /**
  69386. * Sets the ability to have transparent shadow (boolean).
  69387. * @param transparent True if transparent else False
  69388. * @returns the shadow generator allowing fluent coding
  69389. */
  69390. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69391. this._transparencyShadow = transparent;
  69392. return this;
  69393. };
  69394. /**
  69395. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69396. * @returns The render target texture if present otherwise, null
  69397. */
  69398. ShadowGenerator.prototype.getShadowMap = function () {
  69399. return this._shadowMap;
  69400. };
  69401. /**
  69402. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69403. * @returns The render target texture if the shadow map is present otherwise, null
  69404. */
  69405. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69406. if (this._shadowMap2) {
  69407. return this._shadowMap2;
  69408. }
  69409. return this._shadowMap;
  69410. };
  69411. /**
  69412. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69413. * @param mesh Mesh to add
  69414. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69415. * @returns the Shadow Generator itself
  69416. */
  69417. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69418. if (includeDescendants === void 0) { includeDescendants = true; }
  69419. var _a;
  69420. if (!this._shadowMap) {
  69421. return this;
  69422. }
  69423. if (!this._shadowMap.renderList) {
  69424. this._shadowMap.renderList = [];
  69425. }
  69426. this._shadowMap.renderList.push(mesh);
  69427. if (includeDescendants) {
  69428. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69429. }
  69430. return this;
  69431. };
  69432. /**
  69433. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69434. * @param mesh Mesh to remove
  69435. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69436. * @returns the Shadow Generator itself
  69437. */
  69438. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69439. if (includeDescendants === void 0) { includeDescendants = true; }
  69440. if (!this._shadowMap || !this._shadowMap.renderList) {
  69441. return this;
  69442. }
  69443. var index = this._shadowMap.renderList.indexOf(mesh);
  69444. if (index !== -1) {
  69445. this._shadowMap.renderList.splice(index, 1);
  69446. }
  69447. if (includeDescendants) {
  69448. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69449. var child = _a[_i];
  69450. this.removeShadowCaster(child);
  69451. }
  69452. }
  69453. return this;
  69454. };
  69455. /**
  69456. * Returns the associated light object.
  69457. * @returns the light generating the shadow
  69458. */
  69459. ShadowGenerator.prototype.getLight = function () {
  69460. return this._light;
  69461. };
  69462. ShadowGenerator.prototype._initializeGenerator = function () {
  69463. this._light._markMeshesAsLightDirty();
  69464. this._initializeShadowMap();
  69465. };
  69466. ShadowGenerator.prototype._initializeShadowMap = function () {
  69467. var _this = this;
  69468. // Render target
  69469. var engine = this._scene.getEngine();
  69470. if (engine.webGLVersion > 1) {
  69471. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69472. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69473. }
  69474. else {
  69475. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69476. }
  69477. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69478. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69479. this._shadowMap.anisotropicFilteringLevel = 1;
  69480. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69481. this._shadowMap.renderParticles = false;
  69482. this._shadowMap.ignoreCameraViewport = true;
  69483. // Record Face Index before render.
  69484. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69485. _this._currentFaceIndex = faceIndex;
  69486. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69487. engine.setColorWrite(false);
  69488. }
  69489. });
  69490. // Custom render function.
  69491. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69492. // Blur if required afer render.
  69493. this._shadowMap.onAfterUnbindObservable.add(function () {
  69494. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69495. engine.setColorWrite(true);
  69496. }
  69497. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69498. return;
  69499. }
  69500. var shadowMap = _this.getShadowMapForRendering();
  69501. if (shadowMap) {
  69502. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69503. }
  69504. });
  69505. // Clear according to the chosen filter.
  69506. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69507. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69508. this._shadowMap.onClearObservable.add(function (engine) {
  69509. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69510. engine.clear(clearOne, false, true, false);
  69511. }
  69512. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69513. engine.clear(clearZero, true, true, false);
  69514. }
  69515. else {
  69516. engine.clear(clearOne, true, true, false);
  69517. }
  69518. });
  69519. };
  69520. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69521. var _this = this;
  69522. var engine = this._scene.getEngine();
  69523. var targetSize = this._mapSize / this.blurScale;
  69524. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69525. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69526. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69527. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69528. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69529. }
  69530. if (this.useKernelBlur) {
  69531. 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);
  69532. this._kernelBlurXPostprocess.width = targetSize;
  69533. this._kernelBlurXPostprocess.height = targetSize;
  69534. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69535. effect.setTexture("textureSampler", _this._shadowMap);
  69536. });
  69537. 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);
  69538. this._kernelBlurXPostprocess.autoClear = false;
  69539. this._kernelBlurYPostprocess.autoClear = false;
  69540. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69541. this._kernelBlurXPostprocess.packedFloat = true;
  69542. this._kernelBlurYPostprocess.packedFloat = true;
  69543. }
  69544. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69545. }
  69546. else {
  69547. 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);
  69548. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69549. effect.setFloat2("screenSize", targetSize, targetSize);
  69550. effect.setTexture("textureSampler", _this._shadowMap);
  69551. });
  69552. this._boxBlurPostprocess.autoClear = false;
  69553. this._blurPostProcesses = [this._boxBlurPostprocess];
  69554. }
  69555. };
  69556. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69557. var index;
  69558. var engine = this._scene.getEngine();
  69559. if (depthOnlySubMeshes.length) {
  69560. engine.setColorWrite(false);
  69561. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69562. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  69563. }
  69564. engine.setColorWrite(true);
  69565. }
  69566. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69567. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  69568. }
  69569. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69570. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69571. }
  69572. if (this._transparencyShadow) {
  69573. for (index = 0; index < transparentSubMeshes.length; index++) {
  69574. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69575. }
  69576. }
  69577. };
  69578. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69579. var _this = this;
  69580. var mesh = subMesh.getRenderingMesh();
  69581. var scene = this._scene;
  69582. var engine = scene.getEngine();
  69583. var material = subMesh.getMaterial();
  69584. if (!material) {
  69585. return;
  69586. }
  69587. // Culling
  69588. engine.setState(material.backFaceCulling);
  69589. // Managing instances
  69590. var batch = mesh._getInstancesRenderList(subMesh._id);
  69591. if (batch.mustReturn) {
  69592. return;
  69593. }
  69594. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69595. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69596. engine.enableEffect(this._effect);
  69597. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69598. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69599. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69600. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69601. this._effect.setVector3("lightData", this._cachedDirection);
  69602. }
  69603. else {
  69604. this._effect.setVector3("lightData", this._cachedPosition);
  69605. }
  69606. if (scene.activeCamera) {
  69607. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69608. }
  69609. // Alpha test
  69610. if (material && material.needAlphaTesting()) {
  69611. var alphaTexture = material.getAlphaTestTexture();
  69612. if (alphaTexture) {
  69613. this._effect.setTexture("diffuseSampler", alphaTexture);
  69614. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69615. }
  69616. }
  69617. // Bones
  69618. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69619. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69620. }
  69621. // Morph targets
  69622. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69623. if (this.forceBackFacesOnly) {
  69624. engine.setState(true, 0, false, true);
  69625. }
  69626. // Draw
  69627. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69628. if (this.forceBackFacesOnly) {
  69629. engine.setState(true, 0, false, false);
  69630. }
  69631. }
  69632. else {
  69633. // Need to reset refresh rate of the shadowMap
  69634. if (this._shadowMap) {
  69635. this._shadowMap.resetRefreshCounter();
  69636. }
  69637. }
  69638. };
  69639. ShadowGenerator.prototype._applyFilterValues = function () {
  69640. if (!this._shadowMap) {
  69641. return;
  69642. }
  69643. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69644. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69645. }
  69646. else {
  69647. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69648. }
  69649. };
  69650. /**
  69651. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69652. * @param onCompiled Callback triggered at the and of the effects compilation
  69653. * @param options Sets of optional options forcing the compilation with different modes
  69654. */
  69655. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69656. var _this = this;
  69657. var localOptions = __assign({ useInstances: false }, options);
  69658. var shadowMap = this.getShadowMap();
  69659. if (!shadowMap) {
  69660. if (onCompiled) {
  69661. onCompiled(this);
  69662. }
  69663. return;
  69664. }
  69665. var renderList = shadowMap.renderList;
  69666. if (!renderList) {
  69667. if (onCompiled) {
  69668. onCompiled(this);
  69669. }
  69670. return;
  69671. }
  69672. var subMeshes = new Array();
  69673. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69674. var mesh = renderList_1[_i];
  69675. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69676. }
  69677. if (subMeshes.length === 0) {
  69678. if (onCompiled) {
  69679. onCompiled(this);
  69680. }
  69681. return;
  69682. }
  69683. var currentIndex = 0;
  69684. var checkReady = function () {
  69685. if (!_this._scene || !_this._scene.getEngine()) {
  69686. return;
  69687. }
  69688. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69689. currentIndex++;
  69690. if (currentIndex >= subMeshes.length) {
  69691. if (onCompiled) {
  69692. onCompiled(_this);
  69693. }
  69694. return;
  69695. }
  69696. }
  69697. setTimeout(checkReady, 16);
  69698. };
  69699. checkReady();
  69700. };
  69701. /**
  69702. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69703. * @param options Sets of optional options forcing the compilation with different modes
  69704. * @returns A promise that resolves when the compilation completes
  69705. */
  69706. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69707. var _this = this;
  69708. return new Promise(function (resolve) {
  69709. _this.forceCompilation(function () {
  69710. resolve();
  69711. }, options);
  69712. });
  69713. };
  69714. /**
  69715. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69716. * @param subMesh The submesh we want to render in the shadow map
  69717. * @param useInstances Defines wether will draw in the map using instances
  69718. * @returns true if ready otherwise, false
  69719. */
  69720. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69721. var defines = [];
  69722. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69723. defines.push("#define FLOAT");
  69724. }
  69725. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69726. defines.push("#define ESM");
  69727. }
  69728. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69729. defines.push("#define DEPTHTEXTURE");
  69730. }
  69731. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69732. var mesh = subMesh.getMesh();
  69733. var material = subMesh.getMaterial();
  69734. // Normal bias.
  69735. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69736. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69737. defines.push("#define NORMAL");
  69738. if (mesh.nonUniformScaling) {
  69739. defines.push("#define NONUNIFORMSCALING");
  69740. }
  69741. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69742. defines.push("#define DIRECTIONINLIGHTDATA");
  69743. }
  69744. }
  69745. // Alpha test
  69746. if (material && material.needAlphaTesting()) {
  69747. var alphaTexture = material.getAlphaTestTexture();
  69748. if (alphaTexture) {
  69749. defines.push("#define ALPHATEST");
  69750. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69751. attribs.push(BABYLON.VertexBuffer.UVKind);
  69752. defines.push("#define UV1");
  69753. }
  69754. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69755. if (alphaTexture.coordinatesIndex === 1) {
  69756. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69757. defines.push("#define UV2");
  69758. }
  69759. }
  69760. }
  69761. }
  69762. // Bones
  69763. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69764. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69765. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69766. if (mesh.numBoneInfluencers > 4) {
  69767. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69768. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69769. }
  69770. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69771. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69772. }
  69773. else {
  69774. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69775. }
  69776. // Morph targets
  69777. var manager = mesh.morphTargetManager;
  69778. var morphInfluencers = 0;
  69779. if (manager) {
  69780. if (manager.numInfluencers > 0) {
  69781. defines.push("#define MORPHTARGETS");
  69782. morphInfluencers = manager.numInfluencers;
  69783. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69784. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69785. }
  69786. }
  69787. // Instances
  69788. if (useInstances) {
  69789. defines.push("#define INSTANCES");
  69790. attribs.push("world0");
  69791. attribs.push("world1");
  69792. attribs.push("world2");
  69793. attribs.push("world3");
  69794. }
  69795. // Get correct effect
  69796. var join = defines.join("\n");
  69797. if (this._cachedDefines !== join) {
  69798. this._cachedDefines = join;
  69799. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69800. }
  69801. if (!this._effect.isReady()) {
  69802. return false;
  69803. }
  69804. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69805. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69806. this._initializeBlurRTTAndPostProcesses();
  69807. }
  69808. }
  69809. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69810. return false;
  69811. }
  69812. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69813. return false;
  69814. }
  69815. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69816. return false;
  69817. }
  69818. return true;
  69819. };
  69820. /**
  69821. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69822. * @param defines Defines of the material we want to update
  69823. * @param lightIndex Index of the light in the enabled light list of the material
  69824. */
  69825. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69826. var scene = this._scene;
  69827. var light = this._light;
  69828. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69829. return;
  69830. }
  69831. defines["SHADOW" + lightIndex] = true;
  69832. if (this.useContactHardeningShadow) {
  69833. defines["SHADOWPCSS" + lightIndex] = true;
  69834. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69835. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69836. }
  69837. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69838. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69839. }
  69840. // else default to high.
  69841. }
  69842. if (this.usePercentageCloserFiltering) {
  69843. defines["SHADOWPCF" + lightIndex] = true;
  69844. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69845. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69846. }
  69847. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69848. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69849. }
  69850. // else default to high.
  69851. }
  69852. else if (this.usePoissonSampling) {
  69853. defines["SHADOWPOISSON" + lightIndex] = true;
  69854. }
  69855. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69856. defines["SHADOWESM" + lightIndex] = true;
  69857. }
  69858. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69859. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69860. }
  69861. if (light.needCube()) {
  69862. defines["SHADOWCUBE" + lightIndex] = true;
  69863. }
  69864. };
  69865. /**
  69866. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  69867. * defined in the generator but impacting the effect).
  69868. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  69869. * @param effect The effect we are binfing the information for
  69870. */
  69871. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  69872. var light = this._light;
  69873. var scene = this._scene;
  69874. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69875. return;
  69876. }
  69877. var camera = scene.activeCamera;
  69878. if (!camera) {
  69879. return;
  69880. }
  69881. var shadowMap = this.getShadowMap();
  69882. if (!shadowMap) {
  69883. return;
  69884. }
  69885. if (!light.needCube()) {
  69886. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  69887. }
  69888. // Only PCF uses depth stencil texture.
  69889. if (this._filter === ShadowGenerator.FILTER_PCF) {
  69890. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69891. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69892. }
  69893. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  69894. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69895. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  69896. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69897. }
  69898. else {
  69899. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69900. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  69901. }
  69902. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  69903. };
  69904. /**
  69905. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  69906. * (eq to shadow prjection matrix * light transform matrix)
  69907. * @returns The transform matrix used to create the shadow map
  69908. */
  69909. ShadowGenerator.prototype.getTransformMatrix = function () {
  69910. var scene = this._scene;
  69911. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  69912. return this._transformMatrix;
  69913. }
  69914. this._currentRenderID = scene.getRenderId();
  69915. this._currentFaceIndexCache = this._currentFaceIndex;
  69916. var lightPosition = this._light.position;
  69917. if (this._light.computeTransformedInformation()) {
  69918. lightPosition = this._light.transformedPosition;
  69919. }
  69920. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  69921. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  69922. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  69923. }
  69924. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  69925. this._cachedPosition.copyFrom(lightPosition);
  69926. this._cachedDirection.copyFrom(this._lightDirection);
  69927. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  69928. var shadowMap = this.getShadowMap();
  69929. if (shadowMap) {
  69930. var renderList = shadowMap.renderList;
  69931. if (renderList) {
  69932. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  69933. }
  69934. }
  69935. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  69936. }
  69937. return this._transformMatrix;
  69938. };
  69939. /**
  69940. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  69941. * Cube and 2D textures for instance.
  69942. */
  69943. ShadowGenerator.prototype.recreateShadowMap = function () {
  69944. var shadowMap = this._shadowMap;
  69945. if (!shadowMap) {
  69946. return;
  69947. }
  69948. // Track render list.
  69949. var renderList = shadowMap.renderList;
  69950. // Clean up existing data.
  69951. this._disposeRTTandPostProcesses();
  69952. // Reinitializes.
  69953. this._initializeGenerator();
  69954. // Reaffect the filter to ensure a correct fallback if necessary.
  69955. this.filter = this.filter;
  69956. // Reaffect the filter.
  69957. this._applyFilterValues();
  69958. // Reaffect Render List.
  69959. this._shadowMap.renderList = renderList;
  69960. };
  69961. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69962. if (this._shadowMap2) {
  69963. this._shadowMap2.dispose();
  69964. this._shadowMap2 = null;
  69965. }
  69966. if (this._boxBlurPostprocess) {
  69967. this._boxBlurPostprocess.dispose();
  69968. this._boxBlurPostprocess = null;
  69969. }
  69970. if (this._kernelBlurXPostprocess) {
  69971. this._kernelBlurXPostprocess.dispose();
  69972. this._kernelBlurXPostprocess = null;
  69973. }
  69974. if (this._kernelBlurYPostprocess) {
  69975. this._kernelBlurYPostprocess.dispose();
  69976. this._kernelBlurYPostprocess = null;
  69977. }
  69978. this._blurPostProcesses = [];
  69979. };
  69980. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69981. if (this._shadowMap) {
  69982. this._shadowMap.dispose();
  69983. this._shadowMap = null;
  69984. }
  69985. this._disposeBlurPostProcesses();
  69986. };
  69987. /**
  69988. * Disposes the ShadowGenerator.
  69989. * Returns nothing.
  69990. */
  69991. ShadowGenerator.prototype.dispose = function () {
  69992. this._disposeRTTandPostProcesses();
  69993. if (this._light) {
  69994. this._light._shadowGenerator = null;
  69995. this._light._markMeshesAsLightDirty();
  69996. }
  69997. };
  69998. /**
  69999. * Serializes the shadow generator setup to a json object.
  70000. * @returns The serialized JSON object
  70001. */
  70002. ShadowGenerator.prototype.serialize = function () {
  70003. var serializationObject = {};
  70004. var shadowMap = this.getShadowMap();
  70005. if (!shadowMap) {
  70006. return serializationObject;
  70007. }
  70008. serializationObject.lightId = this._light.id;
  70009. serializationObject.mapSize = shadowMap.getRenderSize();
  70010. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70011. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70012. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70013. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70014. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70015. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70016. serializationObject.depthScale = this.depthScale;
  70017. serializationObject.darkness = this.getDarkness();
  70018. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70019. serializationObject.blurKernel = this.blurKernel;
  70020. serializationObject.blurScale = this.blurScale;
  70021. serializationObject.useKernelBlur = this.useKernelBlur;
  70022. serializationObject.transparencyShadow = this._transparencyShadow;
  70023. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70024. serializationObject.bias = this.bias;
  70025. serializationObject.normalBias = this.normalBias;
  70026. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70027. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70028. serializationObject.filteringQuality = this.filteringQuality;
  70029. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70030. serializationObject.renderList = [];
  70031. if (shadowMap.renderList) {
  70032. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70033. var mesh = shadowMap.renderList[meshIndex];
  70034. serializationObject.renderList.push(mesh.id);
  70035. }
  70036. }
  70037. return serializationObject;
  70038. };
  70039. /**
  70040. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70041. * @param parsedShadowGenerator The JSON object to parse
  70042. * @param scene The scene to create the shadow map for
  70043. * @returns The parsed shadow generator
  70044. */
  70045. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70046. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70047. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70048. var shadowMap = shadowGenerator.getShadowMap();
  70049. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70050. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70051. meshes.forEach(function (mesh) {
  70052. if (!shadowMap) {
  70053. return;
  70054. }
  70055. if (!shadowMap.renderList) {
  70056. shadowMap.renderList = [];
  70057. }
  70058. shadowMap.renderList.push(mesh);
  70059. });
  70060. }
  70061. if (parsedShadowGenerator.usePoissonSampling) {
  70062. shadowGenerator.usePoissonSampling = true;
  70063. }
  70064. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70065. shadowGenerator.useExponentialShadowMap = true;
  70066. }
  70067. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70068. shadowGenerator.useBlurExponentialShadowMap = true;
  70069. }
  70070. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70071. shadowGenerator.useCloseExponentialShadowMap = true;
  70072. }
  70073. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70074. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70075. }
  70076. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70077. shadowGenerator.usePercentageCloserFiltering = true;
  70078. }
  70079. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70080. shadowGenerator.useContactHardeningShadow = true;
  70081. }
  70082. if (parsedShadowGenerator.filteringQuality) {
  70083. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70084. }
  70085. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70086. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70087. }
  70088. // Backward compat
  70089. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70090. shadowGenerator.useExponentialShadowMap = true;
  70091. }
  70092. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70093. shadowGenerator.useBlurExponentialShadowMap = true;
  70094. }
  70095. if (parsedShadowGenerator.depthScale) {
  70096. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70097. }
  70098. if (parsedShadowGenerator.blurScale) {
  70099. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70100. }
  70101. if (parsedShadowGenerator.blurBoxOffset) {
  70102. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70103. }
  70104. if (parsedShadowGenerator.useKernelBlur) {
  70105. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70106. }
  70107. if (parsedShadowGenerator.blurKernel) {
  70108. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70109. }
  70110. if (parsedShadowGenerator.bias !== undefined) {
  70111. shadowGenerator.bias = parsedShadowGenerator.bias;
  70112. }
  70113. if (parsedShadowGenerator.normalBias !== undefined) {
  70114. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70115. }
  70116. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70117. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70118. }
  70119. if (parsedShadowGenerator.darkness) {
  70120. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70121. }
  70122. if (parsedShadowGenerator.transparencyShadow) {
  70123. shadowGenerator.setTransparencyShadow(true);
  70124. }
  70125. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70126. return shadowGenerator;
  70127. };
  70128. /**
  70129. * Shadow generator mode None: no filtering applied.
  70130. */
  70131. ShadowGenerator.FILTER_NONE = 0;
  70132. /**
  70133. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70134. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70135. */
  70136. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  70137. /**
  70138. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  70139. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  70140. */
  70141. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  70142. /**
  70143. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  70144. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70145. */
  70146. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  70147. /**
  70148. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  70149. * edge artifacts on steep falloff.
  70150. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70151. */
  70152. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  70153. /**
  70154. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  70155. * edge artifacts on steep falloff.
  70156. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70157. */
  70158. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  70159. /**
  70160. * Shadow generator mode PCF: Percentage Closer Filtering
  70161. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70162. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  70163. */
  70164. ShadowGenerator.FILTER_PCF = 6;
  70165. /**
  70166. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  70167. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  70168. * Contact Hardening
  70169. */
  70170. ShadowGenerator.FILTER_PCSS = 7;
  70171. /**
  70172. * Reserved for PCF and PCSS
  70173. * Highest Quality.
  70174. *
  70175. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  70176. *
  70177. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  70178. */
  70179. ShadowGenerator.QUALITY_HIGH = 0;
  70180. /**
  70181. * Reserved for PCF and PCSS
  70182. * Good tradeoff for quality/perf cross devices
  70183. *
  70184. * Execute PCF on a 3*3 kernel.
  70185. *
  70186. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  70187. */
  70188. ShadowGenerator.QUALITY_MEDIUM = 1;
  70189. /**
  70190. * Reserved for PCF and PCSS
  70191. * The lowest quality but the fastest.
  70192. *
  70193. * Execute PCF on a 1*1 kernel.
  70194. *
  70195. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  70196. */
  70197. ShadowGenerator.QUALITY_LOW = 2;
  70198. return ShadowGenerator;
  70199. }());
  70200. BABYLON.ShadowGenerator = ShadowGenerator;
  70201. })(BABYLON || (BABYLON = {}));
  70202. //# sourceMappingURL=babylon.shadowGenerator.js.map
  70203. var BABYLON;
  70204. (function (BABYLON) {
  70205. var DefaultLoadingScreen = /** @class */ (function () {
  70206. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  70207. if (_loadingText === void 0) { _loadingText = ""; }
  70208. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  70209. var _this = this;
  70210. this._renderingCanvas = _renderingCanvas;
  70211. this._loadingText = _loadingText;
  70212. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  70213. // Resize
  70214. this._resizeLoadingUI = function () {
  70215. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  70216. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  70217. if (!_this._loadingDiv) {
  70218. return;
  70219. }
  70220. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  70221. _this._loadingDiv.style.left = canvasRect.left + "px";
  70222. _this._loadingDiv.style.top = canvasRect.top + "px";
  70223. _this._loadingDiv.style.width = canvasRect.width + "px";
  70224. _this._loadingDiv.style.height = canvasRect.height + "px";
  70225. };
  70226. }
  70227. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  70228. if (this._loadingDiv) {
  70229. // Do not add a loading screen if there is already one
  70230. return;
  70231. }
  70232. this._loadingDiv = document.createElement("div");
  70233. this._loadingDiv.id = "babylonjsLoadingDiv";
  70234. this._loadingDiv.style.opacity = "0";
  70235. this._loadingDiv.style.transition = "opacity 1.5s ease";
  70236. this._loadingDiv.style.pointerEvents = "none";
  70237. // Loading text
  70238. this._loadingTextDiv = document.createElement("div");
  70239. this._loadingTextDiv.style.position = "absolute";
  70240. this._loadingTextDiv.style.left = "0";
  70241. this._loadingTextDiv.style.top = "50%";
  70242. this._loadingTextDiv.style.marginTop = "80px";
  70243. this._loadingTextDiv.style.width = "100%";
  70244. this._loadingTextDiv.style.height = "20px";
  70245. this._loadingTextDiv.style.fontFamily = "Arial";
  70246. this._loadingTextDiv.style.fontSize = "14px";
  70247. this._loadingTextDiv.style.color = "white";
  70248. this._loadingTextDiv.style.textAlign = "center";
  70249. this._loadingTextDiv.innerHTML = "Loading";
  70250. this._loadingDiv.appendChild(this._loadingTextDiv);
  70251. //set the predefined text
  70252. this._loadingTextDiv.innerHTML = this._loadingText;
  70253. // Generating keyframes
  70254. var style = document.createElement('style');
  70255. style.type = 'text/css';
  70256. 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 }";
  70257. style.innerHTML = keyFrames;
  70258. document.getElementsByTagName('head')[0].appendChild(style);
  70259. // Loading img
  70260. var imgBack = new Image();
  70261. 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";
  70262. imgBack.style.position = "absolute";
  70263. imgBack.style.left = "50%";
  70264. imgBack.style.top = "50%";
  70265. imgBack.style.marginLeft = "-60px";
  70266. imgBack.style.marginTop = "-60px";
  70267. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70268. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70269. imgBack.style.transformOrigin = "50% 50%";
  70270. imgBack.style.webkitTransformOrigin = "50% 50%";
  70271. this._loadingDiv.appendChild(imgBack);
  70272. this._resizeLoadingUI();
  70273. window.addEventListener("resize", this._resizeLoadingUI);
  70274. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70275. document.body.appendChild(this._loadingDiv);
  70276. this._loadingDiv.style.opacity = "1";
  70277. };
  70278. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70279. var _this = this;
  70280. if (!this._loadingDiv) {
  70281. return;
  70282. }
  70283. var onTransitionEnd = function () {
  70284. if (!_this._loadingDiv) {
  70285. return;
  70286. }
  70287. document.body.removeChild(_this._loadingDiv);
  70288. window.removeEventListener("resize", _this._resizeLoadingUI);
  70289. _this._loadingDiv = null;
  70290. };
  70291. this._loadingDiv.style.opacity = "0";
  70292. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70293. };
  70294. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70295. set: function (text) {
  70296. this._loadingText = text;
  70297. if (this._loadingTextDiv) {
  70298. this._loadingTextDiv.innerHTML = this._loadingText;
  70299. }
  70300. },
  70301. enumerable: true,
  70302. configurable: true
  70303. });
  70304. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70305. get: function () {
  70306. return this._loadingDivBackgroundColor;
  70307. },
  70308. set: function (color) {
  70309. this._loadingDivBackgroundColor = color;
  70310. if (!this._loadingDiv) {
  70311. return;
  70312. }
  70313. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70314. },
  70315. enumerable: true,
  70316. configurable: true
  70317. });
  70318. return DefaultLoadingScreen;
  70319. }());
  70320. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70321. })(BABYLON || (BABYLON = {}));
  70322. //# sourceMappingURL=babylon.loadingScreen.js.map
  70323. var BABYLON;
  70324. (function (BABYLON) {
  70325. var SceneLoaderProgressEvent = /** @class */ (function () {
  70326. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70327. this.lengthComputable = lengthComputable;
  70328. this.loaded = loaded;
  70329. this.total = total;
  70330. }
  70331. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70332. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70333. };
  70334. return SceneLoaderProgressEvent;
  70335. }());
  70336. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70337. var SceneLoader = /** @class */ (function () {
  70338. function SceneLoader() {
  70339. }
  70340. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70341. get: function () {
  70342. return 0;
  70343. },
  70344. enumerable: true,
  70345. configurable: true
  70346. });
  70347. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70348. get: function () {
  70349. return 1;
  70350. },
  70351. enumerable: true,
  70352. configurable: true
  70353. });
  70354. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70355. get: function () {
  70356. return 2;
  70357. },
  70358. enumerable: true,
  70359. configurable: true
  70360. });
  70361. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70362. get: function () {
  70363. return 3;
  70364. },
  70365. enumerable: true,
  70366. configurable: true
  70367. });
  70368. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70369. get: function () {
  70370. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70371. },
  70372. set: function (value) {
  70373. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70374. },
  70375. enumerable: true,
  70376. configurable: true
  70377. });
  70378. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70379. get: function () {
  70380. return SceneLoader._ShowLoadingScreen;
  70381. },
  70382. set: function (value) {
  70383. SceneLoader._ShowLoadingScreen = value;
  70384. },
  70385. enumerable: true,
  70386. configurable: true
  70387. });
  70388. Object.defineProperty(SceneLoader, "loggingLevel", {
  70389. get: function () {
  70390. return SceneLoader._loggingLevel;
  70391. },
  70392. set: function (value) {
  70393. SceneLoader._loggingLevel = value;
  70394. },
  70395. enumerable: true,
  70396. configurable: true
  70397. });
  70398. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70399. get: function () {
  70400. return SceneLoader._CleanBoneMatrixWeights;
  70401. },
  70402. set: function (value) {
  70403. SceneLoader._CleanBoneMatrixWeights = value;
  70404. },
  70405. enumerable: true,
  70406. configurable: true
  70407. });
  70408. SceneLoader._getDefaultPlugin = function () {
  70409. return SceneLoader._registeredPlugins[".babylon"];
  70410. };
  70411. SceneLoader._getPluginForExtension = function (extension) {
  70412. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70413. if (registeredPlugin) {
  70414. return registeredPlugin;
  70415. }
  70416. 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");
  70417. return SceneLoader._getDefaultPlugin();
  70418. };
  70419. SceneLoader._getPluginForDirectLoad = function (data) {
  70420. for (var extension in SceneLoader._registeredPlugins) {
  70421. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70422. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70423. return SceneLoader._registeredPlugins[extension];
  70424. }
  70425. }
  70426. return SceneLoader._getDefaultPlugin();
  70427. };
  70428. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70429. if (sceneFilename.name) {
  70430. sceneFilename = sceneFilename.name;
  70431. }
  70432. var queryStringPosition = sceneFilename.indexOf("?");
  70433. if (queryStringPosition !== -1) {
  70434. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70435. }
  70436. var dotPosition = sceneFilename.lastIndexOf(".");
  70437. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70438. return SceneLoader._getPluginForExtension(extension);
  70439. };
  70440. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70441. SceneLoader._getDirectLoad = function (sceneFilename) {
  70442. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70443. return sceneFilename.substr(5);
  70444. }
  70445. return null;
  70446. };
  70447. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70448. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70449. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70450. var plugin;
  70451. if (registeredPlugin.plugin.createPlugin) {
  70452. plugin = registeredPlugin.plugin.createPlugin();
  70453. }
  70454. else {
  70455. plugin = registeredPlugin.plugin;
  70456. }
  70457. var useArrayBuffer = registeredPlugin.isBinary;
  70458. var database;
  70459. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  70460. var dataCallback = function (data, responseURL) {
  70461. if (scene.isDisposed) {
  70462. onError("Scene has been disposed");
  70463. return;
  70464. }
  70465. scene.database = database;
  70466. onSuccess(plugin, data, responseURL);
  70467. };
  70468. var request = null;
  70469. var pluginDisposed = false;
  70470. var onDisposeObservable = plugin.onDisposeObservable;
  70471. if (onDisposeObservable) {
  70472. onDisposeObservable.add(function () {
  70473. pluginDisposed = true;
  70474. if (request) {
  70475. request.abort();
  70476. request = null;
  70477. }
  70478. onDispose();
  70479. });
  70480. }
  70481. var manifestChecked = function () {
  70482. if (pluginDisposed) {
  70483. return;
  70484. }
  70485. var url = rootUrl + sceneFilename;
  70486. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  70487. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  70488. } : undefined, database, useArrayBuffer, function (request, exception) {
  70489. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  70490. });
  70491. };
  70492. if (directLoad) {
  70493. dataCallback(directLoad);
  70494. return plugin;
  70495. }
  70496. if (rootUrl.indexOf("file:") === -1) {
  70497. var engine = scene.getEngine();
  70498. var canUseOfflineSupport = engine.enableOfflineSupport;
  70499. if (canUseOfflineSupport) {
  70500. // Also check for exceptions
  70501. var exceptionFound = false;
  70502. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  70503. var regex = _a[_i];
  70504. if (regex.test(rootUrl + sceneFilename)) {
  70505. exceptionFound = true;
  70506. break;
  70507. }
  70508. }
  70509. canUseOfflineSupport = !exceptionFound;
  70510. }
  70511. if (canUseOfflineSupport) {
  70512. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  70513. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  70514. }
  70515. else {
  70516. manifestChecked();
  70517. }
  70518. }
  70519. // Loading file from disk via input file or drag'n'drop
  70520. else {
  70521. var fileOrString = sceneFilename;
  70522. if (fileOrString.name) { // File
  70523. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  70524. }
  70525. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  70526. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  70527. }
  70528. else {
  70529. onError("Unable to find file named " + sceneFilename);
  70530. }
  70531. }
  70532. return plugin;
  70533. };
  70534. // Public functions
  70535. SceneLoader.GetPluginForExtension = function (extension) {
  70536. return SceneLoader._getPluginForExtension(extension).plugin;
  70537. };
  70538. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  70539. return !!SceneLoader._registeredPlugins[extension];
  70540. };
  70541. SceneLoader.RegisterPlugin = function (plugin) {
  70542. if (typeof plugin.extensions === "string") {
  70543. var extension = plugin.extensions;
  70544. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70545. plugin: plugin,
  70546. isBinary: false
  70547. };
  70548. }
  70549. else {
  70550. var extensions = plugin.extensions;
  70551. Object.keys(extensions).forEach(function (extension) {
  70552. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70553. plugin: plugin,
  70554. isBinary: extensions[extension].isBinary
  70555. };
  70556. });
  70557. }
  70558. };
  70559. /**
  70560. * Import meshes into a scene
  70561. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70562. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70563. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70564. * @param scene the instance of BABYLON.Scene to append to
  70565. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  70566. * @param onProgress a callback with a progress event for each file being loaded
  70567. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70568. * @param pluginExtension the extension used to determine the plugin
  70569. * @returns The loaded plugin
  70570. */
  70571. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70572. if (sceneFilename === void 0) { sceneFilename = ""; }
  70573. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70574. if (onSuccess === void 0) { onSuccess = null; }
  70575. if (onProgress === void 0) { onProgress = null; }
  70576. if (onError === void 0) { onError = null; }
  70577. if (pluginExtension === void 0) { pluginExtension = null; }
  70578. if (!scene) {
  70579. BABYLON.Tools.Error("No scene available to import mesh to");
  70580. return null;
  70581. }
  70582. if (!sceneFilename) {
  70583. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70584. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70585. }
  70586. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70587. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70588. return null;
  70589. }
  70590. var loadingToken = {};
  70591. scene._addPendingData(loadingToken);
  70592. var disposeHandler = function () {
  70593. scene._removePendingData(loadingToken);
  70594. };
  70595. var errorHandler = function (message, exception) {
  70596. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70597. if (onError) {
  70598. onError(scene, errorMessage, exception);
  70599. }
  70600. else {
  70601. BABYLON.Tools.Error(errorMessage);
  70602. // should the exception be thrown?
  70603. }
  70604. disposeHandler();
  70605. };
  70606. var progressHandler = onProgress ? function (event) {
  70607. try {
  70608. onProgress(event);
  70609. }
  70610. catch (e) {
  70611. errorHandler("Error in onProgress callback", e);
  70612. }
  70613. } : undefined;
  70614. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70615. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70616. if (onSuccess) {
  70617. try {
  70618. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70619. }
  70620. catch (e) {
  70621. errorHandler("Error in onSuccess callback", e);
  70622. }
  70623. }
  70624. scene._removePendingData(loadingToken);
  70625. };
  70626. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70627. if (plugin.rewriteRootURL) {
  70628. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70629. }
  70630. if (sceneFilename === "") {
  70631. if (sceneFilename === "") {
  70632. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70633. }
  70634. }
  70635. if (plugin.importMesh) {
  70636. var syncedPlugin = plugin;
  70637. var meshes = new Array();
  70638. var particleSystems = new Array();
  70639. var skeletons = new Array();
  70640. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70641. return;
  70642. }
  70643. scene.loadingPluginName = plugin.name;
  70644. successHandler(meshes, particleSystems, skeletons, []);
  70645. }
  70646. else {
  70647. var asyncedPlugin = plugin;
  70648. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70649. scene.loadingPluginName = plugin.name;
  70650. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70651. }).catch(function (error) {
  70652. errorHandler(error.message, error);
  70653. });
  70654. }
  70655. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70656. };
  70657. /**
  70658. * Import meshes into a scene
  70659. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70660. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70661. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70662. * @param scene the instance of BABYLON.Scene to append to
  70663. * @param onProgress a callback with a progress event for each file being loaded
  70664. * @param pluginExtension the extension used to determine the plugin
  70665. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70666. */
  70667. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70668. if (sceneFilename === void 0) { sceneFilename = ""; }
  70669. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70670. if (onProgress === void 0) { onProgress = null; }
  70671. if (pluginExtension === void 0) { pluginExtension = null; }
  70672. return new Promise(function (resolve, reject) {
  70673. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70674. resolve({
  70675. meshes: meshes,
  70676. particleSystems: particleSystems,
  70677. skeletons: skeletons,
  70678. animationGroups: animationGroups
  70679. });
  70680. }, onProgress, function (scene, message, exception) {
  70681. reject(exception || new Error(message));
  70682. }, pluginExtension);
  70683. });
  70684. };
  70685. /**
  70686. * Load a scene
  70687. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70688. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70689. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70690. * @param onSuccess a callback with the scene when import succeeds
  70691. * @param onProgress a callback with a progress event for each file being loaded
  70692. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70693. * @param pluginExtension the extension used to determine the plugin
  70694. * @returns The loaded plugin
  70695. */
  70696. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70697. if (onSuccess === void 0) { onSuccess = null; }
  70698. if (onProgress === void 0) { onProgress = null; }
  70699. if (onError === void 0) { onError = null; }
  70700. if (pluginExtension === void 0) { pluginExtension = null; }
  70701. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70702. };
  70703. /**
  70704. * Load a scene
  70705. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70706. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70707. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70708. * @param onProgress a callback with a progress event for each file being loaded
  70709. * @param pluginExtension the extension used to determine the plugin
  70710. * @returns The loaded scene
  70711. */
  70712. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70713. if (onProgress === void 0) { onProgress = null; }
  70714. if (pluginExtension === void 0) { pluginExtension = null; }
  70715. return new Promise(function (resolve, reject) {
  70716. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70717. resolve(scene);
  70718. }, onProgress, function (scene, message, exception) {
  70719. reject(exception || new Error(message));
  70720. }, pluginExtension);
  70721. });
  70722. };
  70723. /**
  70724. * Append a scene
  70725. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70726. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70727. * @param scene is the instance of BABYLON.Scene to append to
  70728. * @param onSuccess a callback with the scene when import succeeds
  70729. * @param onProgress a callback with a progress event for each file being loaded
  70730. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70731. * @param pluginExtension the extension used to determine the plugin
  70732. * @returns The loaded plugin
  70733. */
  70734. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70735. if (sceneFilename === void 0) { sceneFilename = ""; }
  70736. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70737. if (onSuccess === void 0) { onSuccess = null; }
  70738. if (onProgress === void 0) { onProgress = null; }
  70739. if (onError === void 0) { onError = null; }
  70740. if (pluginExtension === void 0) { pluginExtension = null; }
  70741. if (!scene) {
  70742. BABYLON.Tools.Error("No scene available to append to");
  70743. return null;
  70744. }
  70745. if (!sceneFilename) {
  70746. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70747. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70748. }
  70749. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70750. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70751. return null;
  70752. }
  70753. if (SceneLoader.ShowLoadingScreen) {
  70754. scene.getEngine().displayLoadingUI();
  70755. }
  70756. var loadingToken = {};
  70757. scene._addPendingData(loadingToken);
  70758. var disposeHandler = function () {
  70759. scene._removePendingData(loadingToken);
  70760. scene.getEngine().hideLoadingUI();
  70761. };
  70762. var errorHandler = function (message, exception) {
  70763. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70764. if (onError) {
  70765. onError(scene, errorMessage, exception);
  70766. }
  70767. else {
  70768. BABYLON.Tools.Error(errorMessage);
  70769. // should the exception be thrown?
  70770. }
  70771. disposeHandler();
  70772. };
  70773. var progressHandler = onProgress ? function (event) {
  70774. try {
  70775. onProgress(event);
  70776. }
  70777. catch (e) {
  70778. errorHandler("Error in onProgress callback", e);
  70779. }
  70780. } : undefined;
  70781. var successHandler = function () {
  70782. if (onSuccess) {
  70783. try {
  70784. onSuccess(scene);
  70785. }
  70786. catch (e) {
  70787. errorHandler("Error in onSuccess callback", e);
  70788. }
  70789. }
  70790. scene._removePendingData(loadingToken);
  70791. };
  70792. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70793. if (sceneFilename === "") {
  70794. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70795. }
  70796. if (plugin.load) {
  70797. var syncedPlugin = plugin;
  70798. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70799. return;
  70800. }
  70801. scene.loadingPluginName = plugin.name;
  70802. successHandler();
  70803. }
  70804. else {
  70805. var asyncedPlugin = plugin;
  70806. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70807. scene.loadingPluginName = plugin.name;
  70808. successHandler();
  70809. }).catch(function (error) {
  70810. errorHandler(error.message, error);
  70811. });
  70812. }
  70813. if (SceneLoader.ShowLoadingScreen) {
  70814. scene.executeWhenReady(function () {
  70815. scene.getEngine().hideLoadingUI();
  70816. });
  70817. }
  70818. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70819. };
  70820. /**
  70821. * Append a scene
  70822. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70823. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70824. * @param scene is the instance of BABYLON.Scene to append to
  70825. * @param onProgress a callback with a progress event for each file being loaded
  70826. * @param pluginExtension the extension used to determine the plugin
  70827. * @returns The given scene
  70828. */
  70829. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70830. if (sceneFilename === void 0) { sceneFilename = ""; }
  70831. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70832. if (onProgress === void 0) { onProgress = null; }
  70833. if (pluginExtension === void 0) { pluginExtension = null; }
  70834. return new Promise(function (resolve, reject) {
  70835. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70836. resolve(scene);
  70837. }, onProgress, function (scene, message, exception) {
  70838. reject(exception || new Error(message));
  70839. }, pluginExtension);
  70840. });
  70841. };
  70842. /**
  70843. * Load a scene into an asset container
  70844. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70845. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70846. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70847. * @param onSuccess a callback with the scene when import succeeds
  70848. * @param onProgress a callback with a progress event for each file being loaded
  70849. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70850. * @param pluginExtension the extension used to determine the plugin
  70851. * @returns The loaded plugin
  70852. */
  70853. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70854. if (sceneFilename === void 0) { sceneFilename = ""; }
  70855. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70856. if (onSuccess === void 0) { onSuccess = null; }
  70857. if (onProgress === void 0) { onProgress = null; }
  70858. if (onError === void 0) { onError = null; }
  70859. if (pluginExtension === void 0) { pluginExtension = null; }
  70860. if (!scene) {
  70861. BABYLON.Tools.Error("No scene available to load asset container to");
  70862. return null;
  70863. }
  70864. if (!sceneFilename) {
  70865. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70866. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70867. }
  70868. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70869. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70870. return null;
  70871. }
  70872. var loadingToken = {};
  70873. scene._addPendingData(loadingToken);
  70874. var disposeHandler = function () {
  70875. scene._removePendingData(loadingToken);
  70876. };
  70877. var errorHandler = function (message, exception) {
  70878. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70879. if (onError) {
  70880. onError(scene, errorMessage, exception);
  70881. }
  70882. else {
  70883. BABYLON.Tools.Error(errorMessage);
  70884. // should the exception be thrown?
  70885. }
  70886. disposeHandler();
  70887. };
  70888. var progressHandler = onProgress ? function (event) {
  70889. try {
  70890. onProgress(event);
  70891. }
  70892. catch (e) {
  70893. errorHandler("Error in onProgress callback", e);
  70894. }
  70895. } : undefined;
  70896. var successHandler = function (assets) {
  70897. if (onSuccess) {
  70898. try {
  70899. onSuccess(assets);
  70900. }
  70901. catch (e) {
  70902. errorHandler("Error in onSuccess callback", e);
  70903. }
  70904. }
  70905. scene._removePendingData(loadingToken);
  70906. };
  70907. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70908. if (plugin.loadAssetContainer) {
  70909. var syncedPlugin = plugin;
  70910. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  70911. if (!assetContainer) {
  70912. return;
  70913. }
  70914. scene.loadingPluginName = plugin.name;
  70915. successHandler(assetContainer);
  70916. }
  70917. else if (plugin.loadAssetContainerAsync) {
  70918. var asyncedPlugin = plugin;
  70919. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  70920. scene.loadingPluginName = plugin.name;
  70921. successHandler(assetContainer);
  70922. }).catch(function (error) {
  70923. errorHandler(error.message, error);
  70924. });
  70925. }
  70926. else {
  70927. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  70928. }
  70929. if (SceneLoader.ShowLoadingScreen) {
  70930. scene.executeWhenReady(function () {
  70931. scene.getEngine().hideLoadingUI();
  70932. });
  70933. }
  70934. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70935. };
  70936. /**
  70937. * Load a scene into an asset container
  70938. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  70939. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  70940. * @param scene is the instance of BABYLON.Scene to append to
  70941. * @param onProgress a callback with a progress event for each file being loaded
  70942. * @param pluginExtension the extension used to determine the plugin
  70943. * @returns The loaded asset container
  70944. */
  70945. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70946. if (sceneFilename === void 0) { sceneFilename = ""; }
  70947. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70948. if (onProgress === void 0) { onProgress = null; }
  70949. if (pluginExtension === void 0) { pluginExtension = null; }
  70950. return new Promise(function (resolve, reject) {
  70951. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70952. resolve(assetContainer);
  70953. }, onProgress, function (scene, message, exception) {
  70954. reject(exception || new Error(message));
  70955. }, pluginExtension);
  70956. });
  70957. };
  70958. // Flags
  70959. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70960. SceneLoader._ShowLoadingScreen = true;
  70961. SceneLoader._CleanBoneMatrixWeights = false;
  70962. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70963. // Members
  70964. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70965. SceneLoader._registeredPlugins = {};
  70966. return SceneLoader;
  70967. }());
  70968. BABYLON.SceneLoader = SceneLoader;
  70969. ;
  70970. })(BABYLON || (BABYLON = {}));
  70971. //# sourceMappingURL=babylon.sceneLoader.js.map
  70972. var BABYLON;
  70973. (function (BABYLON) {
  70974. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70975. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70976. var parsedMaterial = parsedData.materials[index];
  70977. if (parsedMaterial.id === id) {
  70978. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70979. }
  70980. }
  70981. return null;
  70982. };
  70983. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70984. for (var i in names) {
  70985. if (mesh.name === names[i]) {
  70986. hierarchyIds.push(mesh.id);
  70987. return true;
  70988. }
  70989. }
  70990. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70991. hierarchyIds.push(mesh.id);
  70992. return true;
  70993. }
  70994. return false;
  70995. };
  70996. var logOperation = function (operation, producer) {
  70997. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70998. };
  70999. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  71000. if (addToScene === void 0) { addToScene = false; }
  71001. var container = new BABYLON.AssetContainer(scene);
  71002. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71003. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71004. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71005. // and avoid problems with multiple concurrent .babylon loads.
  71006. var log = "importScene has failed JSON parse";
  71007. try {
  71008. var parsedData = JSON.parse(data);
  71009. log = "";
  71010. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71011. var index;
  71012. var cache;
  71013. // Lights
  71014. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  71015. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  71016. var parsedLight = parsedData.lights[index];
  71017. var light = BABYLON.Light.Parse(parsedLight, scene);
  71018. if (light) {
  71019. container.lights.push(light);
  71020. log += (index === 0 ? "\n\tLights:" : "");
  71021. log += "\n\t\t" + light.toString(fullDetails);
  71022. }
  71023. }
  71024. }
  71025. // Animations
  71026. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  71027. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  71028. var parsedAnimation = parsedData.animations[index];
  71029. var animation = BABYLON.Animation.Parse(parsedAnimation);
  71030. scene.animations.push(animation);
  71031. container.animations.push(animation);
  71032. log += (index === 0 ? "\n\tAnimations:" : "");
  71033. log += "\n\t\t" + animation.toString(fullDetails);
  71034. }
  71035. }
  71036. // Materials
  71037. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  71038. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71039. var parsedMaterial = parsedData.materials[index];
  71040. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71041. container.materials.push(mat);
  71042. log += (index === 0 ? "\n\tMaterials:" : "");
  71043. log += "\n\t\t" + mat.toString(fullDetails);
  71044. }
  71045. }
  71046. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71047. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  71048. var parsedMultiMaterial = parsedData.multiMaterials[index];
  71049. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71050. container.multiMaterials.push(mmat);
  71051. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  71052. log += "\n\t\t" + mmat.toString(fullDetails);
  71053. }
  71054. }
  71055. // Morph targets
  71056. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71057. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71058. var managerData = _a[_i];
  71059. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  71060. }
  71061. }
  71062. // Skeletons
  71063. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71064. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  71065. var parsedSkeleton = parsedData.skeletons[index];
  71066. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71067. container.skeletons.push(skeleton);
  71068. log += (index === 0 ? "\n\tSkeletons:" : "");
  71069. log += "\n\t\t" + skeleton.toString(fullDetails);
  71070. }
  71071. }
  71072. // Geometries
  71073. var geometries = parsedData.geometries;
  71074. if (geometries !== undefined && geometries !== null) {
  71075. var addedGeometry = new Array();
  71076. // Boxes
  71077. var boxes = geometries.boxes;
  71078. if (boxes !== undefined && boxes !== null) {
  71079. for (index = 0, cache = boxes.length; index < cache; index++) {
  71080. var parsedBox = boxes[index];
  71081. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  71082. }
  71083. }
  71084. // Spheres
  71085. var spheres = geometries.spheres;
  71086. if (spheres !== undefined && spheres !== null) {
  71087. for (index = 0, cache = spheres.length; index < cache; index++) {
  71088. var parsedSphere = spheres[index];
  71089. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  71090. }
  71091. }
  71092. // Cylinders
  71093. var cylinders = geometries.cylinders;
  71094. if (cylinders !== undefined && cylinders !== null) {
  71095. for (index = 0, cache = cylinders.length; index < cache; index++) {
  71096. var parsedCylinder = cylinders[index];
  71097. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  71098. }
  71099. }
  71100. // Toruses
  71101. var toruses = geometries.toruses;
  71102. if (toruses !== undefined && toruses !== null) {
  71103. for (index = 0, cache = toruses.length; index < cache; index++) {
  71104. var parsedTorus = toruses[index];
  71105. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  71106. }
  71107. }
  71108. // Grounds
  71109. var grounds = geometries.grounds;
  71110. if (grounds !== undefined && grounds !== null) {
  71111. for (index = 0, cache = grounds.length; index < cache; index++) {
  71112. var parsedGround = grounds[index];
  71113. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  71114. }
  71115. }
  71116. // Planes
  71117. var planes = geometries.planes;
  71118. if (planes !== undefined && planes !== null) {
  71119. for (index = 0, cache = planes.length; index < cache; index++) {
  71120. var parsedPlane = planes[index];
  71121. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  71122. }
  71123. }
  71124. // TorusKnots
  71125. var torusKnots = geometries.torusKnots;
  71126. if (torusKnots !== undefined && torusKnots !== null) {
  71127. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  71128. var parsedTorusKnot = torusKnots[index];
  71129. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  71130. }
  71131. }
  71132. // VertexData
  71133. var vertexData = geometries.vertexData;
  71134. if (vertexData !== undefined && vertexData !== null) {
  71135. for (index = 0, cache = vertexData.length; index < cache; index++) {
  71136. var parsedVertexData = vertexData[index];
  71137. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  71138. }
  71139. }
  71140. addedGeometry.forEach(function (g) {
  71141. if (g) {
  71142. container.geometries.push(g);
  71143. }
  71144. });
  71145. }
  71146. // Transform nodes
  71147. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  71148. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  71149. var parsedTransformNode = parsedData.transformNodes[index];
  71150. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  71151. container.transformNodes.push(node);
  71152. }
  71153. }
  71154. // Meshes
  71155. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71156. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71157. var parsedMesh = parsedData.meshes[index];
  71158. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71159. container.meshes.push(mesh);
  71160. log += (index === 0 ? "\n\tMeshes:" : "");
  71161. log += "\n\t\t" + mesh.toString(fullDetails);
  71162. }
  71163. }
  71164. // Cameras
  71165. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  71166. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  71167. var parsedCamera = parsedData.cameras[index];
  71168. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  71169. container.cameras.push(camera);
  71170. log += (index === 0 ? "\n\tCameras:" : "");
  71171. log += "\n\t\t" + camera.toString(fullDetails);
  71172. }
  71173. }
  71174. // Browsing all the graph to connect the dots
  71175. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  71176. var camera = scene.cameras[index];
  71177. if (camera._waitingParentId) {
  71178. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  71179. camera._waitingParentId = null;
  71180. }
  71181. }
  71182. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71183. var light_1 = scene.lights[index];
  71184. if (light_1 && light_1._waitingParentId) {
  71185. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  71186. light_1._waitingParentId = null;
  71187. }
  71188. }
  71189. // Sounds
  71190. // TODO: add sound
  71191. var loadedSounds = [];
  71192. var loadedSound;
  71193. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  71194. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  71195. var parsedSound = parsedData.sounds[index];
  71196. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  71197. if (!parsedSound.url)
  71198. parsedSound.url = parsedSound.name;
  71199. if (!loadedSounds[parsedSound.url]) {
  71200. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  71201. loadedSounds[parsedSound.url] = loadedSound;
  71202. container.sounds.push(loadedSound);
  71203. }
  71204. else {
  71205. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  71206. }
  71207. }
  71208. else {
  71209. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  71210. }
  71211. }
  71212. }
  71213. loadedSounds = [];
  71214. // Connect parents & children and parse actions
  71215. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  71216. var transformNode = scene.transformNodes[index];
  71217. if (transformNode._waitingParentId) {
  71218. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  71219. transformNode._waitingParentId = null;
  71220. }
  71221. }
  71222. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71223. var mesh = scene.meshes[index];
  71224. if (mesh._waitingParentId) {
  71225. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  71226. mesh._waitingParentId = null;
  71227. }
  71228. if (mesh._waitingActions) {
  71229. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  71230. mesh._waitingActions = null;
  71231. }
  71232. }
  71233. // freeze world matrix application
  71234. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71235. var currentMesh = scene.meshes[index];
  71236. if (currentMesh._waitingFreezeWorldMatrix) {
  71237. currentMesh.freezeWorldMatrix();
  71238. currentMesh._waitingFreezeWorldMatrix = null;
  71239. }
  71240. else {
  71241. currentMesh.computeWorldMatrix(true);
  71242. }
  71243. }
  71244. // Shadows
  71245. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71246. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71247. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71248. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71249. // SG would be available on their associated lights
  71250. }
  71251. }
  71252. // Lights exclusions / inclusions
  71253. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  71254. var light_2 = scene.lights[index];
  71255. // Excluded check
  71256. if (light_2._excludedMeshesIds.length > 0) {
  71257. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  71258. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  71259. if (excludedMesh) {
  71260. light_2.excludedMeshes.push(excludedMesh);
  71261. }
  71262. }
  71263. light_2._excludedMeshesIds = [];
  71264. }
  71265. // Included check
  71266. if (light_2._includedOnlyMeshesIds.length > 0) {
  71267. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71268. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71269. if (includedOnlyMesh) {
  71270. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71271. }
  71272. }
  71273. light_2._includedOnlyMeshesIds = [];
  71274. }
  71275. }
  71276. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71277. // Actions (scene)
  71278. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71279. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71280. }
  71281. if (!addToScene) {
  71282. container.removeAllFromScene();
  71283. }
  71284. }
  71285. catch (err) {
  71286. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  71287. if (onError) {
  71288. onError(msg, err);
  71289. }
  71290. else {
  71291. BABYLON.Tools.Log(msg);
  71292. throw err;
  71293. }
  71294. }
  71295. finally {
  71296. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71297. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71298. }
  71299. }
  71300. return container;
  71301. };
  71302. BABYLON.SceneLoader.RegisterPlugin({
  71303. name: "babylon.js",
  71304. extensions: ".babylon",
  71305. canDirectLoad: function (data) {
  71306. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71307. return true;
  71308. }
  71309. return false;
  71310. },
  71311. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71312. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71313. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71314. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71315. // and avoid problems with multiple concurrent .babylon loads.
  71316. var log = "importMesh has failed JSON parse";
  71317. try {
  71318. var parsedData = JSON.parse(data);
  71319. log = "";
  71320. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71321. if (!meshesNames) {
  71322. meshesNames = null;
  71323. }
  71324. else if (!Array.isArray(meshesNames)) {
  71325. meshesNames = [meshesNames];
  71326. }
  71327. var hierarchyIds = new Array();
  71328. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71329. var loadedSkeletonsIds = [];
  71330. var loadedMaterialsIds = [];
  71331. var index;
  71332. var cache;
  71333. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71334. var parsedMesh = parsedData.meshes[index];
  71335. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71336. if (meshesNames !== null) {
  71337. // Remove found mesh name from list.
  71338. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71339. }
  71340. //Geometry?
  71341. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71342. //does the file contain geometries?
  71343. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71344. //find the correct geometry and add it to the scene
  71345. var found = false;
  71346. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71347. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71348. return;
  71349. }
  71350. else {
  71351. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71352. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71353. switch (geometryType) {
  71354. case "boxes":
  71355. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71356. break;
  71357. case "spheres":
  71358. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71359. break;
  71360. case "cylinders":
  71361. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71362. break;
  71363. case "toruses":
  71364. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71365. break;
  71366. case "grounds":
  71367. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71368. break;
  71369. case "planes":
  71370. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71371. break;
  71372. case "torusKnots":
  71373. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71374. break;
  71375. case "vertexData":
  71376. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71377. break;
  71378. }
  71379. found = true;
  71380. }
  71381. });
  71382. }
  71383. });
  71384. if (found === false) {
  71385. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71386. }
  71387. }
  71388. }
  71389. // Material ?
  71390. if (parsedMesh.materialId) {
  71391. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71392. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71393. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71394. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71395. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71396. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71397. var subMatId = parsedMultiMaterial.materials[matIndex];
  71398. loadedMaterialsIds.push(subMatId);
  71399. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71400. if (mat) {
  71401. log += "\n\tMaterial " + mat.toString(fullDetails);
  71402. }
  71403. }
  71404. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71405. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71406. if (mmat) {
  71407. materialFound = true;
  71408. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71409. }
  71410. break;
  71411. }
  71412. }
  71413. }
  71414. if (materialFound === false) {
  71415. loadedMaterialsIds.push(parsedMesh.materialId);
  71416. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71417. if (!mat) {
  71418. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71419. }
  71420. else {
  71421. log += "\n\tMaterial " + mat.toString(fullDetails);
  71422. }
  71423. }
  71424. }
  71425. // Skeleton ?
  71426. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71427. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71428. if (skeletonAlreadyLoaded === false) {
  71429. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71430. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71431. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71432. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71433. skeletons.push(skeleton);
  71434. loadedSkeletonsIds.push(parsedSkeleton.id);
  71435. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71436. }
  71437. }
  71438. }
  71439. }
  71440. // Morph targets ?
  71441. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71442. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71443. var managerData = _a[_i];
  71444. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71445. }
  71446. }
  71447. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71448. meshes.push(mesh);
  71449. log += "\n\tMesh " + mesh.toString(fullDetails);
  71450. }
  71451. }
  71452. // Connecting parents
  71453. var currentMesh;
  71454. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71455. currentMesh = scene.meshes[index];
  71456. if (currentMesh._waitingParentId) {
  71457. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71458. currentMesh._waitingParentId = null;
  71459. }
  71460. }
  71461. // freeze and compute world matrix application
  71462. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71463. currentMesh = scene.meshes[index];
  71464. if (currentMesh._waitingFreezeWorldMatrix) {
  71465. currentMesh.freezeWorldMatrix();
  71466. currentMesh._waitingFreezeWorldMatrix = null;
  71467. }
  71468. else {
  71469. currentMesh.computeWorldMatrix(true);
  71470. }
  71471. }
  71472. }
  71473. // Particles
  71474. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  71475. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  71476. if (parser) {
  71477. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  71478. var parsedParticleSystem = parsedData.particleSystems[index];
  71479. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  71480. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  71481. }
  71482. }
  71483. }
  71484. }
  71485. return true;
  71486. }
  71487. catch (err) {
  71488. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  71489. if (onError) {
  71490. onError(msg, err);
  71491. }
  71492. else {
  71493. BABYLON.Tools.Log(msg);
  71494. throw err;
  71495. }
  71496. }
  71497. finally {
  71498. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71499. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71500. }
  71501. }
  71502. return false;
  71503. },
  71504. load: function (scene, data, rootUrl, onError) {
  71505. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71506. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71507. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71508. // and avoid problems with multiple concurrent .babylon loads.
  71509. var log = "importScene has failed JSON parse";
  71510. try {
  71511. var parsedData = JSON.parse(data);
  71512. log = "";
  71513. // Scene
  71514. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  71515. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  71516. }
  71517. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  71518. scene.autoClear = parsedData.autoClear;
  71519. }
  71520. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  71521. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  71522. }
  71523. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  71524. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  71525. }
  71526. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  71527. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  71528. }
  71529. // Fog
  71530. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  71531. scene.fogMode = parsedData.fogMode;
  71532. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  71533. scene.fogStart = parsedData.fogStart;
  71534. scene.fogEnd = parsedData.fogEnd;
  71535. scene.fogDensity = parsedData.fogDensity;
  71536. log += "\tFog mode for scene: ";
  71537. switch (scene.fogMode) {
  71538. // getters not compiling, so using hardcoded
  71539. case 1:
  71540. log += "exp\n";
  71541. break;
  71542. case 2:
  71543. log += "exp2\n";
  71544. break;
  71545. case 3:
  71546. log += "linear\n";
  71547. break;
  71548. }
  71549. }
  71550. //Physics
  71551. if (parsedData.physicsEnabled) {
  71552. var physicsPlugin;
  71553. if (parsedData.physicsEngine === "cannon") {
  71554. physicsPlugin = new BABYLON.CannonJSPlugin();
  71555. }
  71556. else if (parsedData.physicsEngine === "oimo") {
  71557. physicsPlugin = new BABYLON.OimoJSPlugin();
  71558. }
  71559. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  71560. //else - default engine, which is currently oimo
  71561. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  71562. scene.enablePhysics(physicsGravity, physicsPlugin);
  71563. }
  71564. // Metadata
  71565. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  71566. scene.metadata = parsedData.metadata;
  71567. }
  71568. //collisions, if defined. otherwise, default is true
  71569. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  71570. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71571. }
  71572. scene.workerCollisions = !!parsedData.workerCollisions;
  71573. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71574. if (!container) {
  71575. return false;
  71576. }
  71577. if (parsedData.autoAnimate) {
  71578. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71579. }
  71580. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71581. scene.setActiveCameraByID(parsedData.activeCameraID);
  71582. }
  71583. // Environment texture
  71584. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71585. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71586. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71587. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71588. if (parsedData.environmentTextureRotationY) {
  71589. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71590. }
  71591. scene.environmentTexture = hdrTexture;
  71592. }
  71593. else {
  71594. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71595. if (parsedData.environmentTextureRotationY) {
  71596. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71597. }
  71598. scene.environmentTexture = cubeTexture;
  71599. }
  71600. if (parsedData.createDefaultSkybox === true) {
  71601. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71602. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71603. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71604. }
  71605. }
  71606. // Finish
  71607. return true;
  71608. }
  71609. catch (err) {
  71610. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71611. if (onError) {
  71612. onError(msg, err);
  71613. }
  71614. else {
  71615. BABYLON.Tools.Log(msg);
  71616. throw err;
  71617. }
  71618. }
  71619. finally {
  71620. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71621. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71622. }
  71623. }
  71624. return false;
  71625. },
  71626. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71627. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71628. return container;
  71629. }
  71630. });
  71631. })(BABYLON || (BABYLON = {}));
  71632. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71633. var BABYLON;
  71634. (function (BABYLON) {
  71635. var FilesInput = /** @class */ (function () {
  71636. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71637. this.onProcessFileCallback = function () { return true; };
  71638. this._engine = engine;
  71639. this._currentScene = scene;
  71640. this._sceneLoadedCallback = sceneLoadedCallback;
  71641. this._progressCallback = progressCallback;
  71642. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71643. this._textureLoadingCallback = textureLoadingCallback;
  71644. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71645. this._onReloadCallback = onReloadCallback;
  71646. this._errorCallback = errorCallback;
  71647. }
  71648. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71649. var _this = this;
  71650. if (elementToMonitor) {
  71651. this._elementToMonitor = elementToMonitor;
  71652. this._dragEnterHandler = function (e) { _this.drag(e); };
  71653. this._dragOverHandler = function (e) { _this.drag(e); };
  71654. this._dropHandler = function (e) { _this.drop(e); };
  71655. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71656. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71657. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71658. }
  71659. };
  71660. FilesInput.prototype.dispose = function () {
  71661. if (!this._elementToMonitor) {
  71662. return;
  71663. }
  71664. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71665. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71666. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71667. };
  71668. FilesInput.prototype.renderFunction = function () {
  71669. if (this._additionalRenderLoopLogicCallback) {
  71670. this._additionalRenderLoopLogicCallback();
  71671. }
  71672. if (this._currentScene) {
  71673. if (this._textureLoadingCallback) {
  71674. var remaining = this._currentScene.getWaitingItemsCount();
  71675. if (remaining > 0) {
  71676. this._textureLoadingCallback(remaining);
  71677. }
  71678. }
  71679. this._currentScene.render();
  71680. }
  71681. };
  71682. FilesInput.prototype.drag = function (e) {
  71683. e.stopPropagation();
  71684. e.preventDefault();
  71685. };
  71686. FilesInput.prototype.drop = function (eventDrop) {
  71687. eventDrop.stopPropagation();
  71688. eventDrop.preventDefault();
  71689. this.loadFiles(eventDrop);
  71690. };
  71691. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71692. var _this = this;
  71693. var reader = folder.createReader();
  71694. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71695. reader.readEntries(function (entries) {
  71696. remaining.count += entries.length;
  71697. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71698. var entry = entries_1[_i];
  71699. if (entry.isFile) {
  71700. entry.file(function (file) {
  71701. file.correctName = relativePath + file.name;
  71702. files.push(file);
  71703. if (--remaining.count === 0) {
  71704. callback();
  71705. }
  71706. });
  71707. }
  71708. else if (entry.isDirectory) {
  71709. _this._traverseFolder(entry, files, remaining, callback);
  71710. }
  71711. }
  71712. if (--remaining.count) {
  71713. callback();
  71714. }
  71715. });
  71716. };
  71717. FilesInput.prototype._processFiles = function (files) {
  71718. for (var i = 0; i < files.length; i++) {
  71719. var name = files[i].correctName.toLowerCase();
  71720. var extension = name.split('.').pop();
  71721. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71722. continue;
  71723. }
  71724. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71725. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71726. this._sceneFileToLoad = files[i];
  71727. }
  71728. else {
  71729. FilesInput.FilesToLoad[name] = files[i];
  71730. }
  71731. }
  71732. };
  71733. FilesInput.prototype.loadFiles = function (event) {
  71734. var _this = this;
  71735. if (this._startingProcessingFilesCallback)
  71736. this._startingProcessingFilesCallback();
  71737. // Handling data transfer via drag'n'drop
  71738. if (event && event.dataTransfer && event.dataTransfer.files) {
  71739. this._filesToLoad = event.dataTransfer.files;
  71740. }
  71741. // Handling files from input files
  71742. if (event && event.target && event.target.files) {
  71743. this._filesToLoad = event.target.files;
  71744. }
  71745. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71746. var files_1 = new Array();
  71747. var folders = [];
  71748. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71749. for (var i = 0; i < this._filesToLoad.length; i++) {
  71750. var fileToLoad = this._filesToLoad[i];
  71751. var name_1 = fileToLoad.name.toLowerCase();
  71752. var entry = void 0;
  71753. fileToLoad.correctName = name_1;
  71754. if (items) {
  71755. var item = items[i];
  71756. if (item.getAsEntry) {
  71757. entry = item.getAsEntry();
  71758. }
  71759. else if (item.webkitGetAsEntry) {
  71760. entry = item.webkitGetAsEntry();
  71761. }
  71762. }
  71763. if (!entry) {
  71764. files_1.push(fileToLoad);
  71765. }
  71766. else {
  71767. if (entry.isDirectory) {
  71768. folders.push(entry);
  71769. }
  71770. else {
  71771. files_1.push(fileToLoad);
  71772. }
  71773. }
  71774. }
  71775. if (folders.length === 0) {
  71776. this._processFiles(files_1);
  71777. this._processReload();
  71778. }
  71779. else {
  71780. var remaining = { count: folders.length };
  71781. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71782. var folder = folders_1[_i];
  71783. this._traverseFolder(folder, files_1, remaining, function () {
  71784. _this._processFiles(files_1);
  71785. if (remaining.count === 0) {
  71786. _this._processReload();
  71787. }
  71788. });
  71789. }
  71790. }
  71791. }
  71792. };
  71793. FilesInput.prototype._processReload = function () {
  71794. if (this._onReloadCallback) {
  71795. this._onReloadCallback(this._sceneFileToLoad);
  71796. }
  71797. else {
  71798. this.reload();
  71799. }
  71800. };
  71801. FilesInput.prototype.reload = function () {
  71802. var _this = this;
  71803. // If a scene file has been provided
  71804. if (this._sceneFileToLoad) {
  71805. if (this._currentScene) {
  71806. if (BABYLON.Tools.errorsCount > 0) {
  71807. BABYLON.Tools.ClearLogCache();
  71808. }
  71809. this._engine.stopRenderLoop();
  71810. }
  71811. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71812. if (_this._progressCallback) {
  71813. _this._progressCallback(progress);
  71814. }
  71815. }).then(function (scene) {
  71816. if (_this._currentScene) {
  71817. _this._currentScene.dispose();
  71818. }
  71819. _this._currentScene = scene;
  71820. if (_this._sceneLoadedCallback) {
  71821. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71822. }
  71823. // Wait for textures and shaders to be ready
  71824. _this._currentScene.executeWhenReady(function () {
  71825. _this._engine.runRenderLoop(function () {
  71826. _this.renderFunction();
  71827. });
  71828. });
  71829. }).catch(function (error) {
  71830. if (_this._errorCallback) {
  71831. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71832. }
  71833. });
  71834. }
  71835. else {
  71836. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71837. }
  71838. };
  71839. FilesInput.FilesToLoad = {};
  71840. return FilesInput;
  71841. }());
  71842. BABYLON.FilesInput = FilesInput;
  71843. })(BABYLON || (BABYLON = {}));
  71844. //# sourceMappingURL=babylon.filesInput.js.map
  71845. var BABYLON;
  71846. (function (BABYLON) {
  71847. var Tags = /** @class */ (function () {
  71848. function Tags() {
  71849. }
  71850. Tags.EnableFor = function (obj) {
  71851. obj._tags = obj._tags || {};
  71852. obj.hasTags = function () {
  71853. return Tags.HasTags(obj);
  71854. };
  71855. obj.addTags = function (tagsString) {
  71856. return Tags.AddTagsTo(obj, tagsString);
  71857. };
  71858. obj.removeTags = function (tagsString) {
  71859. return Tags.RemoveTagsFrom(obj, tagsString);
  71860. };
  71861. obj.matchesTagsQuery = function (tagsQuery) {
  71862. return Tags.MatchesQuery(obj, tagsQuery);
  71863. };
  71864. };
  71865. Tags.DisableFor = function (obj) {
  71866. delete obj._tags;
  71867. delete obj.hasTags;
  71868. delete obj.addTags;
  71869. delete obj.removeTags;
  71870. delete obj.matchesTagsQuery;
  71871. };
  71872. Tags.HasTags = function (obj) {
  71873. if (!obj._tags) {
  71874. return false;
  71875. }
  71876. return !BABYLON.Tools.IsEmpty(obj._tags);
  71877. };
  71878. Tags.GetTags = function (obj, asString) {
  71879. if (asString === void 0) { asString = true; }
  71880. if (!obj._tags) {
  71881. return null;
  71882. }
  71883. if (asString) {
  71884. var tagsArray = [];
  71885. for (var tag in obj._tags) {
  71886. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  71887. tagsArray.push(tag);
  71888. }
  71889. }
  71890. return tagsArray.join(" ");
  71891. }
  71892. else {
  71893. return obj._tags;
  71894. }
  71895. };
  71896. // the tags 'true' and 'false' are reserved and cannot be used as tags
  71897. // a tag cannot start with '||', '&&', and '!'
  71898. // it cannot contain whitespaces
  71899. Tags.AddTagsTo = function (obj, tagsString) {
  71900. if (!tagsString) {
  71901. return;
  71902. }
  71903. if (typeof tagsString !== "string") {
  71904. return;
  71905. }
  71906. var tags = tagsString.split(" ");
  71907. tags.forEach(function (tag, index, array) {
  71908. Tags._AddTagTo(obj, tag);
  71909. });
  71910. };
  71911. Tags._AddTagTo = function (obj, tag) {
  71912. tag = tag.trim();
  71913. if (tag === "" || tag === "true" || tag === "false") {
  71914. return;
  71915. }
  71916. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  71917. return;
  71918. }
  71919. Tags.EnableFor(obj);
  71920. obj._tags[tag] = true;
  71921. };
  71922. Tags.RemoveTagsFrom = function (obj, tagsString) {
  71923. if (!Tags.HasTags(obj)) {
  71924. return;
  71925. }
  71926. var tags = tagsString.split(" ");
  71927. for (var t in tags) {
  71928. Tags._RemoveTagFrom(obj, tags[t]);
  71929. }
  71930. };
  71931. Tags._RemoveTagFrom = function (obj, tag) {
  71932. delete obj._tags[tag];
  71933. };
  71934. Tags.MatchesQuery = function (obj, tagsQuery) {
  71935. if (tagsQuery === undefined) {
  71936. return true;
  71937. }
  71938. if (tagsQuery === "") {
  71939. return Tags.HasTags(obj);
  71940. }
  71941. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  71942. };
  71943. return Tags;
  71944. }());
  71945. BABYLON.Tags = Tags;
  71946. })(BABYLON || (BABYLON = {}));
  71947. //# sourceMappingURL=babylon.tags.js.map
  71948. var BABYLON;
  71949. (function (BABYLON) {
  71950. /**
  71951. * Class used to evalaute queries containing `and` and `or` operators
  71952. */
  71953. var AndOrNotEvaluator = /** @class */ (function () {
  71954. function AndOrNotEvaluator() {
  71955. }
  71956. /**
  71957. * Evaluate a query
  71958. * @param query defines the query to evaluate
  71959. * @param evaluateCallback defines the callback used to filter result
  71960. * @returns true if the query matches
  71961. */
  71962. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71963. if (!query.match(/\([^\(\)]*\)/g)) {
  71964. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71965. }
  71966. else {
  71967. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71968. // remove parenthesis
  71969. r = r.slice(1, r.length - 1);
  71970. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71971. });
  71972. }
  71973. if (query === "true") {
  71974. return true;
  71975. }
  71976. if (query === "false") {
  71977. return false;
  71978. }
  71979. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71980. };
  71981. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71982. evaluateCallback = evaluateCallback || (function (r) {
  71983. return r === "true" ? true : false;
  71984. });
  71985. var result;
  71986. var or = parenthesisContent.split("||");
  71987. for (var i in or) {
  71988. if (or.hasOwnProperty(i)) {
  71989. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71990. var and = ori.split("&&");
  71991. if (and.length > 1) {
  71992. for (var j = 0; j < and.length; ++j) {
  71993. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71994. if (andj !== "true" && andj !== "false") {
  71995. if (andj[0] === "!") {
  71996. result = !evaluateCallback(andj.substring(1));
  71997. }
  71998. else {
  71999. result = evaluateCallback(andj);
  72000. }
  72001. }
  72002. else {
  72003. result = andj === "true" ? true : false;
  72004. }
  72005. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  72006. ori = "false";
  72007. break;
  72008. }
  72009. }
  72010. }
  72011. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  72012. result = true;
  72013. break;
  72014. }
  72015. // result equals false (or undefined)
  72016. if (ori !== "true" && ori !== "false") {
  72017. if (ori[0] === "!") {
  72018. result = !evaluateCallback(ori.substring(1));
  72019. }
  72020. else {
  72021. result = evaluateCallback(ori);
  72022. }
  72023. }
  72024. else {
  72025. result = ori === "true" ? true : false;
  72026. }
  72027. }
  72028. }
  72029. // the whole parenthesis scope is replaced by 'true' or 'false'
  72030. return result ? "true" : "false";
  72031. };
  72032. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  72033. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  72034. // remove whitespaces
  72035. r = r.replace(/[\s]/g, function () { return ""; });
  72036. return r.length % 2 ? "!" : "";
  72037. });
  72038. booleanString = booleanString.trim();
  72039. if (booleanString === "!true") {
  72040. booleanString = "false";
  72041. }
  72042. else if (booleanString === "!false") {
  72043. booleanString = "true";
  72044. }
  72045. return booleanString;
  72046. };
  72047. return AndOrNotEvaluator;
  72048. }());
  72049. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  72050. })(BABYLON || (BABYLON = {}));
  72051. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  72052. var BABYLON;
  72053. (function (BABYLON) {
  72054. /**
  72055. * Class used to enable access to IndexedDB
  72056. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  72057. */
  72058. var Database = /** @class */ (function () {
  72059. /**
  72060. * Creates a new Database
  72061. * @param urlToScene defines the url to load the scene
  72062. * @param callbackManifestChecked defines the callback to use when manifest is checked
  72063. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  72064. */
  72065. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  72066. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  72067. var _this = this;
  72068. // Handling various flavors of prefixed version of IndexedDB
  72069. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  72070. this.callbackManifestChecked = callbackManifestChecked;
  72071. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  72072. this.db = null;
  72073. this._enableSceneOffline = false;
  72074. this._enableTexturesOffline = false;
  72075. this.manifestVersionFound = 0;
  72076. this.mustUpdateRessources = false;
  72077. this.hasReachedQuota = false;
  72078. if (!Database.IDBStorageEnabled) {
  72079. this.callbackManifestChecked(true);
  72080. }
  72081. else {
  72082. if (disableManifestCheck) {
  72083. this._enableSceneOffline = true;
  72084. this._enableTexturesOffline = true;
  72085. this.manifestVersionFound = 1;
  72086. BABYLON.Tools.SetImmediate(function () {
  72087. _this.callbackManifestChecked(true);
  72088. });
  72089. }
  72090. else {
  72091. this._checkManifestFile();
  72092. }
  72093. }
  72094. }
  72095. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  72096. /**
  72097. * Gets a boolean indicating if scene must be saved in the database
  72098. */
  72099. get: function () {
  72100. return this._enableSceneOffline;
  72101. },
  72102. enumerable: true,
  72103. configurable: true
  72104. });
  72105. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  72106. /**
  72107. * Gets a boolean indicating if textures must be saved in the database
  72108. */
  72109. get: function () {
  72110. return this._enableTexturesOffline;
  72111. },
  72112. enumerable: true,
  72113. configurable: true
  72114. });
  72115. Database.prototype._checkManifestFile = function () {
  72116. var _this = this;
  72117. var noManifestFile = function () {
  72118. _this._enableSceneOffline = false;
  72119. _this._enableTexturesOffline = false;
  72120. _this.callbackManifestChecked(false);
  72121. };
  72122. var timeStampUsed = false;
  72123. var manifestURL = this.currentSceneUrl + ".manifest";
  72124. var xhr = new XMLHttpRequest();
  72125. if (navigator.onLine) {
  72126. // Adding a timestamp to by-pass browsers' cache
  72127. timeStampUsed = true;
  72128. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  72129. }
  72130. xhr.open("GET", manifestURL, true);
  72131. xhr.addEventListener("load", function () {
  72132. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  72133. try {
  72134. var manifestFile = JSON.parse(xhr.response);
  72135. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  72136. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  72137. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  72138. _this.manifestVersionFound = manifestFile.version;
  72139. }
  72140. if (_this.callbackManifestChecked) {
  72141. _this.callbackManifestChecked(true);
  72142. }
  72143. }
  72144. catch (ex) {
  72145. noManifestFile();
  72146. }
  72147. }
  72148. else {
  72149. noManifestFile();
  72150. }
  72151. }, false);
  72152. xhr.addEventListener("error", function (event) {
  72153. if (timeStampUsed) {
  72154. timeStampUsed = false;
  72155. // Let's retry without the timeStamp
  72156. // It could fail when coupled with HTML5 Offline API
  72157. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  72158. xhr.open("GET", retryManifestURL, true);
  72159. xhr.send();
  72160. }
  72161. else {
  72162. noManifestFile();
  72163. }
  72164. }, false);
  72165. try {
  72166. xhr.send();
  72167. }
  72168. catch (ex) {
  72169. BABYLON.Tools.Error("Error on XHR send request.");
  72170. this.callbackManifestChecked(false);
  72171. }
  72172. };
  72173. /**
  72174. * Open the database and make it available
  72175. * @param successCallback defines the callback to call on success
  72176. * @param errorCallback defines the callback to call on error
  72177. */
  72178. Database.prototype.openAsync = function (successCallback, errorCallback) {
  72179. var _this = this;
  72180. var handleError = function () {
  72181. _this.isSupported = false;
  72182. if (errorCallback)
  72183. errorCallback();
  72184. };
  72185. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  72186. // Your browser doesn't support IndexedDB
  72187. this.isSupported = false;
  72188. if (errorCallback)
  72189. errorCallback();
  72190. }
  72191. else {
  72192. // If the DB hasn't been opened or created yet
  72193. if (!this.db) {
  72194. this.hasReachedQuota = false;
  72195. this.isSupported = true;
  72196. var request = this.idbFactory.open("babylonjs", 1);
  72197. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  72198. request.onerror = function (event) {
  72199. handleError();
  72200. };
  72201. // executes when a version change transaction cannot complete due to other active transactions
  72202. request.onblocked = function (event) {
  72203. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  72204. handleError();
  72205. };
  72206. // DB has been opened successfully
  72207. request.onsuccess = function (event) {
  72208. _this.db = request.result;
  72209. successCallback();
  72210. };
  72211. // Initialization of the DB. Creating Scenes & Textures stores
  72212. request.onupgradeneeded = function (event) {
  72213. _this.db = (event.target).result;
  72214. if (_this.db) {
  72215. try {
  72216. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  72217. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  72218. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  72219. }
  72220. catch (ex) {
  72221. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  72222. handleError();
  72223. }
  72224. }
  72225. };
  72226. }
  72227. // DB has already been created and opened
  72228. else {
  72229. if (successCallback)
  72230. successCallback();
  72231. }
  72232. }
  72233. };
  72234. /**
  72235. * Loads an image from the database
  72236. * @param url defines the url to load from
  72237. * @param image defines the target DOM image
  72238. */
  72239. Database.prototype.loadImageFromDB = function (url, image) {
  72240. var _this = this;
  72241. var completeURL = Database._ReturnFullUrlLocation(url);
  72242. var saveAndLoadImage = function () {
  72243. if (!_this.hasReachedQuota && _this.db !== null) {
  72244. // the texture is not yet in the DB, let's try to save it
  72245. _this._saveImageIntoDBAsync(completeURL, image);
  72246. }
  72247. // If the texture is not in the DB and we've reached the DB quota limit
  72248. // let's load it directly from the web
  72249. else {
  72250. image.src = url;
  72251. }
  72252. };
  72253. if (!this.mustUpdateRessources) {
  72254. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  72255. }
  72256. // First time we're download the images or update requested in the manifest file by a version change
  72257. else {
  72258. saveAndLoadImage();
  72259. }
  72260. };
  72261. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72262. if (this.isSupported && this.db !== null) {
  72263. var texture;
  72264. var transaction = this.db.transaction(["textures"]);
  72265. transaction.onabort = function (event) {
  72266. image.src = url;
  72267. };
  72268. transaction.oncomplete = function (event) {
  72269. var blobTextureURL;
  72270. if (texture) {
  72271. var URL = window.URL || window.webkitURL;
  72272. blobTextureURL = URL.createObjectURL(texture.data);
  72273. image.onerror = function () {
  72274. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72275. image.src = url;
  72276. };
  72277. image.src = blobTextureURL;
  72278. }
  72279. else {
  72280. notInDBCallback();
  72281. }
  72282. };
  72283. var getRequest = transaction.objectStore("textures").get(url);
  72284. getRequest.onsuccess = function (event) {
  72285. texture = (event.target).result;
  72286. };
  72287. getRequest.onerror = function (event) {
  72288. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72289. image.src = url;
  72290. };
  72291. }
  72292. else {
  72293. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72294. image.src = url;
  72295. }
  72296. };
  72297. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72298. var _this = this;
  72299. if (this.isSupported) {
  72300. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72301. var generateBlobUrl = function () {
  72302. var blobTextureURL;
  72303. if (blob) {
  72304. var URL = window.URL || window.webkitURL;
  72305. try {
  72306. blobTextureURL = URL.createObjectURL(blob);
  72307. }
  72308. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72309. catch (ex) {
  72310. blobTextureURL = URL.createObjectURL(blob);
  72311. }
  72312. }
  72313. if (blobTextureURL) {
  72314. image.src = blobTextureURL;
  72315. }
  72316. };
  72317. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72318. var xhr = new XMLHttpRequest(), blob;
  72319. xhr.open("GET", url, true);
  72320. xhr.responseType = "blob";
  72321. xhr.addEventListener("load", function () {
  72322. if (xhr.status === 200 && _this.db) {
  72323. // Blob as response (XHR2)
  72324. blob = xhr.response;
  72325. var transaction = _this.db.transaction(["textures"], "readwrite");
  72326. // the transaction could abort because of a QuotaExceededError error
  72327. transaction.onabort = function (event) {
  72328. try {
  72329. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72330. var srcElement = (event.srcElement || event.target);
  72331. var error = srcElement.error;
  72332. if (error && error.name === "QuotaExceededError") {
  72333. _this.hasReachedQuota = true;
  72334. }
  72335. }
  72336. catch (ex) { }
  72337. generateBlobUrl();
  72338. };
  72339. transaction.oncomplete = function (event) {
  72340. generateBlobUrl();
  72341. };
  72342. var newTexture = { textureUrl: url, data: blob };
  72343. try {
  72344. // Put the blob into the dabase
  72345. var addRequest = transaction.objectStore("textures").put(newTexture);
  72346. addRequest.onsuccess = function (event) {
  72347. };
  72348. addRequest.onerror = function (event) {
  72349. generateBlobUrl();
  72350. };
  72351. }
  72352. catch (ex) {
  72353. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72354. if (ex.code === 25) {
  72355. Database.IsUASupportingBlobStorage = false;
  72356. }
  72357. image.src = url;
  72358. }
  72359. }
  72360. else {
  72361. image.src = url;
  72362. }
  72363. }, false);
  72364. xhr.addEventListener("error", function (event) {
  72365. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72366. image.src = url;
  72367. }, false);
  72368. xhr.send();
  72369. }
  72370. else {
  72371. image.src = url;
  72372. }
  72373. }
  72374. else {
  72375. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72376. image.src = url;
  72377. }
  72378. };
  72379. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72380. var _this = this;
  72381. var updateVersion = function () {
  72382. // the version is not yet in the DB or we need to update it
  72383. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72384. };
  72385. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72386. };
  72387. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72388. var _this = this;
  72389. if (this.isSupported && this.db) {
  72390. var version;
  72391. try {
  72392. var transaction = this.db.transaction(["versions"]);
  72393. transaction.oncomplete = function (event) {
  72394. if (version) {
  72395. // If the version in the JSON file is different from the version in DB
  72396. if (_this.manifestVersionFound !== version.data) {
  72397. _this.mustUpdateRessources = true;
  72398. updateInDBCallback();
  72399. }
  72400. else {
  72401. callback(version.data);
  72402. }
  72403. }
  72404. // version was not found in DB
  72405. else {
  72406. _this.mustUpdateRessources = true;
  72407. updateInDBCallback();
  72408. }
  72409. };
  72410. transaction.onabort = function (event) {
  72411. callback(-1);
  72412. };
  72413. var getRequest = transaction.objectStore("versions").get(url);
  72414. getRequest.onsuccess = function (event) {
  72415. version = (event.target).result;
  72416. };
  72417. getRequest.onerror = function (event) {
  72418. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72419. callback(-1);
  72420. };
  72421. }
  72422. catch (ex) {
  72423. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72424. callback(-1);
  72425. }
  72426. }
  72427. else {
  72428. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72429. callback(-1);
  72430. }
  72431. };
  72432. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72433. var _this = this;
  72434. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72435. try {
  72436. // Open a transaction to the database
  72437. var transaction = this.db.transaction(["versions"], "readwrite");
  72438. // the transaction could abort because of a QuotaExceededError error
  72439. transaction.onabort = function (event) {
  72440. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72441. var error = event.srcElement['error'];
  72442. if (error && error.name === "QuotaExceededError") {
  72443. _this.hasReachedQuota = true;
  72444. }
  72445. }
  72446. catch (ex) { }
  72447. callback(-1);
  72448. };
  72449. transaction.oncomplete = function (event) {
  72450. callback(_this.manifestVersionFound);
  72451. };
  72452. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72453. // Put the scene into the database
  72454. var addRequest = transaction.objectStore("versions").put(newVersion);
  72455. addRequest.onsuccess = function (event) {
  72456. };
  72457. addRequest.onerror = function (event) {
  72458. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72459. };
  72460. }
  72461. catch (ex) {
  72462. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  72463. callback(-1);
  72464. }
  72465. }
  72466. else {
  72467. callback(-1);
  72468. }
  72469. };
  72470. /**
  72471. * Loads a file from database
  72472. * @param url defines the URL to load from
  72473. * @param sceneLoaded defines a callback to call on success
  72474. * @param progressCallBack defines a callback to call when progress changed
  72475. * @param errorCallback defines a callback to call on error
  72476. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  72477. */
  72478. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  72479. var _this = this;
  72480. var completeUrl = Database._ReturnFullUrlLocation(url);
  72481. var saveAndLoadFile = function () {
  72482. // the scene is not yet in the DB, let's try to save it
  72483. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72484. };
  72485. this._checkVersionFromDB(completeUrl, function (version) {
  72486. if (version !== -1) {
  72487. if (!_this.mustUpdateRessources) {
  72488. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  72489. }
  72490. else {
  72491. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72492. }
  72493. }
  72494. else {
  72495. if (errorCallback) {
  72496. errorCallback();
  72497. }
  72498. }
  72499. });
  72500. };
  72501. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  72502. if (this.isSupported && this.db) {
  72503. var targetStore;
  72504. if (url.indexOf(".babylon") !== -1) {
  72505. targetStore = "scenes";
  72506. }
  72507. else {
  72508. targetStore = "textures";
  72509. }
  72510. var file;
  72511. var transaction = this.db.transaction([targetStore]);
  72512. transaction.oncomplete = function (event) {
  72513. if (file) {
  72514. callback(file.data);
  72515. }
  72516. // file was not found in DB
  72517. else {
  72518. notInDBCallback();
  72519. }
  72520. };
  72521. transaction.onabort = function (event) {
  72522. notInDBCallback();
  72523. };
  72524. var getRequest = transaction.objectStore(targetStore).get(url);
  72525. getRequest.onsuccess = function (event) {
  72526. file = (event.target).result;
  72527. };
  72528. getRequest.onerror = function (event) {
  72529. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  72530. notInDBCallback();
  72531. };
  72532. }
  72533. else {
  72534. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72535. callback();
  72536. }
  72537. };
  72538. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  72539. var _this = this;
  72540. if (this.isSupported) {
  72541. var targetStore;
  72542. if (url.indexOf(".babylon") !== -1) {
  72543. targetStore = "scenes";
  72544. }
  72545. else {
  72546. targetStore = "textures";
  72547. }
  72548. // Create XHR
  72549. var xhr = new XMLHttpRequest();
  72550. var fileData;
  72551. xhr.open("GET", url + "?" + Date.now(), true);
  72552. if (useArrayBuffer) {
  72553. xhr.responseType = "arraybuffer";
  72554. }
  72555. if (progressCallback) {
  72556. xhr.onprogress = progressCallback;
  72557. }
  72558. xhr.addEventListener("load", function () {
  72559. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  72560. // Blob as response (XHR2)
  72561. //fileData = xhr.responseText;
  72562. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  72563. if (!_this.hasReachedQuota && _this.db) {
  72564. // Open a transaction to the database
  72565. var transaction = _this.db.transaction([targetStore], "readwrite");
  72566. // the transaction could abort because of a QuotaExceededError error
  72567. transaction.onabort = function (event) {
  72568. try {
  72569. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72570. var error = event.srcElement['error'];
  72571. if (error && error.name === "QuotaExceededError") {
  72572. _this.hasReachedQuota = true;
  72573. }
  72574. }
  72575. catch (ex) { }
  72576. callback(fileData);
  72577. };
  72578. transaction.oncomplete = function (event) {
  72579. callback(fileData);
  72580. };
  72581. var newFile;
  72582. if (targetStore === "scenes") {
  72583. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72584. }
  72585. else {
  72586. newFile = { textureUrl: url, data: fileData };
  72587. }
  72588. try {
  72589. // Put the scene into the database
  72590. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72591. addRequest.onsuccess = function (event) {
  72592. };
  72593. addRequest.onerror = function (event) {
  72594. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72595. };
  72596. }
  72597. catch (ex) {
  72598. callback(fileData);
  72599. }
  72600. }
  72601. else {
  72602. callback(fileData);
  72603. }
  72604. }
  72605. else {
  72606. if (xhr.status >= 400 && errorCallback) {
  72607. errorCallback(xhr);
  72608. }
  72609. else {
  72610. callback();
  72611. }
  72612. }
  72613. }, false);
  72614. xhr.addEventListener("error", function (event) {
  72615. BABYLON.Tools.Error("error on XHR request.");
  72616. callback();
  72617. }, false);
  72618. xhr.send();
  72619. }
  72620. else {
  72621. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72622. callback();
  72623. }
  72624. };
  72625. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72626. Database.IsUASupportingBlobStorage = true;
  72627. /** Gets a boolean indicating if Database storate is enabled */
  72628. Database.IDBStorageEnabled = true;
  72629. Database._ParseURL = function (url) {
  72630. var a = document.createElement('a');
  72631. a.href = url;
  72632. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72633. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72634. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72635. return absLocation;
  72636. };
  72637. Database._ReturnFullUrlLocation = function (url) {
  72638. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72639. return (Database._ParseURL(window.location.href) + url);
  72640. }
  72641. else {
  72642. return url;
  72643. }
  72644. };
  72645. return Database;
  72646. }());
  72647. BABYLON.Database = Database;
  72648. })(BABYLON || (BABYLON = {}));
  72649. //# sourceMappingURL=babylon.database.js.map
  72650. var BABYLON;
  72651. (function (BABYLON) {
  72652. var FresnelParameters = /** @class */ (function () {
  72653. function FresnelParameters() {
  72654. this._isEnabled = true;
  72655. this.leftColor = BABYLON.Color3.White();
  72656. this.rightColor = BABYLON.Color3.Black();
  72657. this.bias = 0;
  72658. this.power = 1;
  72659. }
  72660. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72661. get: function () {
  72662. return this._isEnabled;
  72663. },
  72664. set: function (value) {
  72665. if (this._isEnabled === value) {
  72666. return;
  72667. }
  72668. this._isEnabled = value;
  72669. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72670. },
  72671. enumerable: true,
  72672. configurable: true
  72673. });
  72674. FresnelParameters.prototype.clone = function () {
  72675. var newFresnelParameters = new FresnelParameters();
  72676. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72677. return newFresnelParameters;
  72678. };
  72679. FresnelParameters.prototype.serialize = function () {
  72680. var serializationObject = {};
  72681. serializationObject.isEnabled = this.isEnabled;
  72682. serializationObject.leftColor = this.leftColor.asArray();
  72683. serializationObject.rightColor = this.rightColor.asArray();
  72684. serializationObject.bias = this.bias;
  72685. serializationObject.power = this.power;
  72686. return serializationObject;
  72687. };
  72688. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72689. var fresnelParameters = new FresnelParameters();
  72690. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72691. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72692. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72693. fresnelParameters.bias = parsedFresnelParameters.bias;
  72694. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72695. return fresnelParameters;
  72696. };
  72697. return FresnelParameters;
  72698. }());
  72699. BABYLON.FresnelParameters = FresnelParameters;
  72700. })(BABYLON || (BABYLON = {}));
  72701. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72702. var BABYLON;
  72703. (function (BABYLON) {
  72704. var MultiMaterial = /** @class */ (function (_super) {
  72705. __extends(MultiMaterial, _super);
  72706. function MultiMaterial(name, scene) {
  72707. var _this = _super.call(this, name, scene, true) || this;
  72708. scene.multiMaterials.push(_this);
  72709. _this.subMaterials = new Array();
  72710. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72711. return _this;
  72712. }
  72713. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72714. get: function () {
  72715. return this._subMaterials;
  72716. },
  72717. set: function (value) {
  72718. this._subMaterials = value;
  72719. this._hookArray(value);
  72720. },
  72721. enumerable: true,
  72722. configurable: true
  72723. });
  72724. MultiMaterial.prototype._hookArray = function (array) {
  72725. var _this = this;
  72726. var oldPush = array.push;
  72727. array.push = function () {
  72728. var items = [];
  72729. for (var _i = 0; _i < arguments.length; _i++) {
  72730. items[_i] = arguments[_i];
  72731. }
  72732. var result = oldPush.apply(array, items);
  72733. _this._markAllSubMeshesAsTexturesDirty();
  72734. return result;
  72735. };
  72736. var oldSplice = array.splice;
  72737. array.splice = function (index, deleteCount) {
  72738. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72739. _this._markAllSubMeshesAsTexturesDirty();
  72740. return deleted;
  72741. };
  72742. };
  72743. // Properties
  72744. MultiMaterial.prototype.getSubMaterial = function (index) {
  72745. if (index < 0 || index >= this.subMaterials.length) {
  72746. return this.getScene().defaultMaterial;
  72747. }
  72748. return this.subMaterials[index];
  72749. };
  72750. MultiMaterial.prototype.getActiveTextures = function () {
  72751. var _a;
  72752. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72753. if (subMaterial) {
  72754. return subMaterial.getActiveTextures();
  72755. }
  72756. else {
  72757. return [];
  72758. }
  72759. }));
  72760. };
  72761. // Methods
  72762. MultiMaterial.prototype.getClassName = function () {
  72763. return "MultiMaterial";
  72764. };
  72765. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72766. for (var index = 0; index < this.subMaterials.length; index++) {
  72767. var subMaterial = this.subMaterials[index];
  72768. if (subMaterial) {
  72769. if (subMaterial.storeEffectOnSubMeshes) {
  72770. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72771. return false;
  72772. }
  72773. continue;
  72774. }
  72775. if (!subMaterial.isReady(mesh)) {
  72776. return false;
  72777. }
  72778. }
  72779. }
  72780. return true;
  72781. };
  72782. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72783. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72784. for (var index = 0; index < this.subMaterials.length; index++) {
  72785. var subMaterial = null;
  72786. var current = this.subMaterials[index];
  72787. if (cloneChildren && current) {
  72788. subMaterial = current.clone(name + "-" + current.name);
  72789. }
  72790. else {
  72791. subMaterial = this.subMaterials[index];
  72792. }
  72793. newMultiMaterial.subMaterials.push(subMaterial);
  72794. }
  72795. return newMultiMaterial;
  72796. };
  72797. MultiMaterial.prototype.serialize = function () {
  72798. var serializationObject = {};
  72799. serializationObject.name = this.name;
  72800. serializationObject.id = this.id;
  72801. if (BABYLON.Tags) {
  72802. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72803. }
  72804. serializationObject.materials = [];
  72805. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72806. var subMat = this.subMaterials[matIndex];
  72807. if (subMat) {
  72808. serializationObject.materials.push(subMat.id);
  72809. }
  72810. else {
  72811. serializationObject.materials.push(null);
  72812. }
  72813. }
  72814. return serializationObject;
  72815. };
  72816. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72817. var scene = this.getScene();
  72818. if (!scene) {
  72819. return;
  72820. }
  72821. var index = scene.multiMaterials.indexOf(this);
  72822. if (index >= 0) {
  72823. scene.multiMaterials.splice(index, 1);
  72824. }
  72825. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72826. };
  72827. return MultiMaterial;
  72828. }(BABYLON.Material));
  72829. BABYLON.MultiMaterial = MultiMaterial;
  72830. })(BABYLON || (BABYLON = {}));
  72831. //# sourceMappingURL=babylon.multiMaterial.js.map
  72832. var BABYLON;
  72833. (function (BABYLON) {
  72834. var FreeCameraTouchInput = /** @class */ (function () {
  72835. function FreeCameraTouchInput() {
  72836. this._offsetX = null;
  72837. this._offsetY = null;
  72838. this._pointerPressed = new Array();
  72839. this.touchAngularSensibility = 200000.0;
  72840. this.touchMoveSensibility = 250.0;
  72841. }
  72842. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72843. var _this = this;
  72844. var previousPosition = null;
  72845. if (this._pointerInput === undefined) {
  72846. this._onLostFocus = function (evt) {
  72847. _this._offsetX = null;
  72848. _this._offsetY = null;
  72849. };
  72850. this._pointerInput = function (p, s) {
  72851. var evt = p.event;
  72852. if (evt.pointerType === "mouse") {
  72853. return;
  72854. }
  72855. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72856. if (!noPreventDefault) {
  72857. evt.preventDefault();
  72858. }
  72859. _this._pointerPressed.push(evt.pointerId);
  72860. if (_this._pointerPressed.length !== 1) {
  72861. return;
  72862. }
  72863. previousPosition = {
  72864. x: evt.clientX,
  72865. y: evt.clientY
  72866. };
  72867. }
  72868. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  72869. if (!noPreventDefault) {
  72870. evt.preventDefault();
  72871. }
  72872. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72873. if (index === -1) {
  72874. return;
  72875. }
  72876. _this._pointerPressed.splice(index, 1);
  72877. if (index != 0) {
  72878. return;
  72879. }
  72880. previousPosition = null;
  72881. _this._offsetX = null;
  72882. _this._offsetY = null;
  72883. }
  72884. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  72885. if (!noPreventDefault) {
  72886. evt.preventDefault();
  72887. }
  72888. if (!previousPosition) {
  72889. return;
  72890. }
  72891. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72892. if (index != 0) {
  72893. return;
  72894. }
  72895. _this._offsetX = evt.clientX - previousPosition.x;
  72896. _this._offsetY = -(evt.clientY - previousPosition.y);
  72897. }
  72898. };
  72899. }
  72900. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  72901. if (this._onLostFocus) {
  72902. element.addEventListener("blur", this._onLostFocus);
  72903. }
  72904. };
  72905. FreeCameraTouchInput.prototype.detachControl = function (element) {
  72906. if (this._pointerInput && element) {
  72907. if (this._observer) {
  72908. this.camera.getScene().onPointerObservable.remove(this._observer);
  72909. this._observer = null;
  72910. }
  72911. if (this._onLostFocus) {
  72912. element.removeEventListener("blur", this._onLostFocus);
  72913. this._onLostFocus = null;
  72914. }
  72915. this._pointerPressed = [];
  72916. this._offsetX = null;
  72917. this._offsetY = null;
  72918. }
  72919. };
  72920. FreeCameraTouchInput.prototype.checkInputs = function () {
  72921. if (this._offsetX && this._offsetY) {
  72922. var camera = this.camera;
  72923. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  72924. if (this._pointerPressed.length > 1) {
  72925. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  72926. }
  72927. else {
  72928. var speed = camera._computeLocalCameraSpeed();
  72929. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  72930. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  72931. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  72932. }
  72933. }
  72934. };
  72935. FreeCameraTouchInput.prototype.getClassName = function () {
  72936. return "FreeCameraTouchInput";
  72937. };
  72938. FreeCameraTouchInput.prototype.getSimpleName = function () {
  72939. return "touch";
  72940. };
  72941. __decorate([
  72942. BABYLON.serialize()
  72943. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  72944. __decorate([
  72945. BABYLON.serialize()
  72946. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  72947. return FreeCameraTouchInput;
  72948. }());
  72949. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  72950. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72951. })(BABYLON || (BABYLON = {}));
  72952. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72953. var BABYLON;
  72954. (function (BABYLON) {
  72955. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72956. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72957. });
  72958. // We're mainly based on the logic defined into the FreeCamera code
  72959. var TouchCamera = /** @class */ (function (_super) {
  72960. __extends(TouchCamera, _super);
  72961. //-- end properties for backward compatibility for inputs
  72962. function TouchCamera(name, position, scene) {
  72963. var _this = _super.call(this, name, position, scene) || this;
  72964. _this.inputs.addTouch();
  72965. _this._setupInputs();
  72966. return _this;
  72967. }
  72968. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72969. //-- Begin properties for backward compatibility for inputs
  72970. get: function () {
  72971. var touch = this.inputs.attached["touch"];
  72972. if (touch)
  72973. return touch.touchAngularSensibility;
  72974. return 0;
  72975. },
  72976. set: function (value) {
  72977. var touch = this.inputs.attached["touch"];
  72978. if (touch)
  72979. touch.touchAngularSensibility = value;
  72980. },
  72981. enumerable: true,
  72982. configurable: true
  72983. });
  72984. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72985. get: function () {
  72986. var touch = this.inputs.attached["touch"];
  72987. if (touch)
  72988. return touch.touchMoveSensibility;
  72989. return 0;
  72990. },
  72991. set: function (value) {
  72992. var touch = this.inputs.attached["touch"];
  72993. if (touch)
  72994. touch.touchMoveSensibility = value;
  72995. },
  72996. enumerable: true,
  72997. configurable: true
  72998. });
  72999. TouchCamera.prototype.getClassName = function () {
  73000. return "TouchCamera";
  73001. };
  73002. /** @hidden */
  73003. TouchCamera.prototype._setupInputs = function () {
  73004. var mouse = this.inputs.attached["mouse"];
  73005. if (mouse) {
  73006. mouse.touchEnabled = false;
  73007. }
  73008. };
  73009. return TouchCamera;
  73010. }(BABYLON.FreeCamera));
  73011. BABYLON.TouchCamera = TouchCamera;
  73012. })(BABYLON || (BABYLON = {}));
  73013. //# sourceMappingURL=babylon.touchCamera.js.map
  73014. var BABYLON;
  73015. (function (BABYLON) {
  73016. var ProceduralTexture = /** @class */ (function (_super) {
  73017. __extends(ProceduralTexture, _super);
  73018. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  73019. if (fallbackTexture === void 0) { fallbackTexture = null; }
  73020. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73021. if (isCube === void 0) { isCube = false; }
  73022. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73023. _this.isCube = isCube;
  73024. _this.isEnabled = true;
  73025. _this._currentRefreshId = -1;
  73026. _this._refreshRate = 1;
  73027. _this._vertexBuffers = {};
  73028. _this._uniforms = new Array();
  73029. _this._samplers = new Array();
  73030. /** @hidden */
  73031. _this._textures = {};
  73032. _this._floats = {};
  73033. _this._ints = {};
  73034. _this._floatsArrays = {};
  73035. _this._colors3 = {};
  73036. _this._colors4 = {};
  73037. _this._vectors2 = {};
  73038. _this._vectors3 = {};
  73039. _this._matrices = {};
  73040. _this._fallbackTextureUsed = false;
  73041. scene = _this.getScene();
  73042. scene.proceduralTextures.push(_this);
  73043. _this._engine = scene.getEngine();
  73044. _this.name = name;
  73045. _this.isRenderTarget = true;
  73046. _this._size = size;
  73047. _this._generateMipMaps = generateMipMaps;
  73048. _this.setFragment(fragment);
  73049. _this._fallbackTexture = fallbackTexture;
  73050. if (isCube) {
  73051. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  73052. _this.setFloat("face", 0);
  73053. }
  73054. else {
  73055. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  73056. }
  73057. // VBO
  73058. var vertices = [];
  73059. vertices.push(1, 1);
  73060. vertices.push(-1, 1);
  73061. vertices.push(-1, -1);
  73062. vertices.push(1, -1);
  73063. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73064. _this._createIndexBuffer();
  73065. return _this;
  73066. }
  73067. ProceduralTexture.prototype._createIndexBuffer = function () {
  73068. var engine = this._engine;
  73069. // Indices
  73070. var indices = [];
  73071. indices.push(0);
  73072. indices.push(1);
  73073. indices.push(2);
  73074. indices.push(0);
  73075. indices.push(2);
  73076. indices.push(3);
  73077. this._indexBuffer = engine.createIndexBuffer(indices);
  73078. };
  73079. /** @hidden */
  73080. ProceduralTexture.prototype._rebuild = function () {
  73081. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73082. if (vb) {
  73083. vb._rebuild();
  73084. }
  73085. this._createIndexBuffer();
  73086. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  73087. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  73088. }
  73089. };
  73090. ProceduralTexture.prototype.reset = function () {
  73091. if (this._effect === undefined) {
  73092. return;
  73093. }
  73094. var engine = this._engine;
  73095. engine._releaseEffect(this._effect);
  73096. };
  73097. ProceduralTexture.prototype.isReady = function () {
  73098. var _this = this;
  73099. var engine = this._engine;
  73100. var shaders;
  73101. if (!this._fragment) {
  73102. return false;
  73103. }
  73104. if (this._fallbackTextureUsed) {
  73105. return true;
  73106. }
  73107. if (this._fragment.fragmentElement !== undefined) {
  73108. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  73109. }
  73110. else {
  73111. shaders = { vertex: "procedural", fragment: this._fragment };
  73112. }
  73113. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  73114. _this.releaseInternalTexture();
  73115. if (_this._fallbackTexture) {
  73116. _this._texture = _this._fallbackTexture._texture;
  73117. if (_this._texture) {
  73118. _this._texture.incrementReferences();
  73119. }
  73120. }
  73121. _this._fallbackTextureUsed = true;
  73122. });
  73123. return this._effect.isReady();
  73124. };
  73125. ProceduralTexture.prototype.resetRefreshCounter = function () {
  73126. this._currentRefreshId = -1;
  73127. };
  73128. ProceduralTexture.prototype.setFragment = function (fragment) {
  73129. this._fragment = fragment;
  73130. };
  73131. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  73132. get: function () {
  73133. return this._refreshRate;
  73134. },
  73135. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  73136. set: function (value) {
  73137. this._refreshRate = value;
  73138. this.resetRefreshCounter();
  73139. },
  73140. enumerable: true,
  73141. configurable: true
  73142. });
  73143. /** @hidden */
  73144. ProceduralTexture.prototype._shouldRender = function () {
  73145. if (!this.isEnabled || !this.isReady() || !this._texture) {
  73146. return false;
  73147. }
  73148. if (this._fallbackTextureUsed) {
  73149. return false;
  73150. }
  73151. if (this._currentRefreshId === -1) { // At least render once
  73152. this._currentRefreshId = 1;
  73153. return true;
  73154. }
  73155. if (this.refreshRate === this._currentRefreshId) {
  73156. this._currentRefreshId = 1;
  73157. return true;
  73158. }
  73159. this._currentRefreshId++;
  73160. return false;
  73161. };
  73162. ProceduralTexture.prototype.getRenderSize = function () {
  73163. return this._size;
  73164. };
  73165. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  73166. if (this._fallbackTextureUsed) {
  73167. return;
  73168. }
  73169. this.releaseInternalTexture();
  73170. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  73171. // Update properties
  73172. this._size = size;
  73173. this._generateMipMaps = generateMipMaps;
  73174. };
  73175. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  73176. if (this._uniforms.indexOf(uniformName) === -1) {
  73177. this._uniforms.push(uniformName);
  73178. }
  73179. };
  73180. ProceduralTexture.prototype.setTexture = function (name, texture) {
  73181. if (this._samplers.indexOf(name) === -1) {
  73182. this._samplers.push(name);
  73183. }
  73184. this._textures[name] = texture;
  73185. return this;
  73186. };
  73187. ProceduralTexture.prototype.setFloat = function (name, value) {
  73188. this._checkUniform(name);
  73189. this._floats[name] = value;
  73190. return this;
  73191. };
  73192. /**
  73193. * Set the value of an uniform to an integer value
  73194. * @param name defines the name of the uniform
  73195. * @param value defines the value to set
  73196. * @returns the current procedural texture
  73197. */
  73198. ProceduralTexture.prototype.setInt = function (name, value) {
  73199. this._checkUniform(name);
  73200. this._ints[name] = value;
  73201. return this;
  73202. };
  73203. ProceduralTexture.prototype.setFloats = function (name, value) {
  73204. this._checkUniform(name);
  73205. this._floatsArrays[name] = value;
  73206. return this;
  73207. };
  73208. ProceduralTexture.prototype.setColor3 = function (name, value) {
  73209. this._checkUniform(name);
  73210. this._colors3[name] = value;
  73211. return this;
  73212. };
  73213. ProceduralTexture.prototype.setColor4 = function (name, value) {
  73214. this._checkUniform(name);
  73215. this._colors4[name] = value;
  73216. return this;
  73217. };
  73218. ProceduralTexture.prototype.setVector2 = function (name, value) {
  73219. this._checkUniform(name);
  73220. this._vectors2[name] = value;
  73221. return this;
  73222. };
  73223. ProceduralTexture.prototype.setVector3 = function (name, value) {
  73224. this._checkUniform(name);
  73225. this._vectors3[name] = value;
  73226. return this;
  73227. };
  73228. ProceduralTexture.prototype.setMatrix = function (name, value) {
  73229. this._checkUniform(name);
  73230. this._matrices[name] = value;
  73231. return this;
  73232. };
  73233. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73234. var scene = this.getScene();
  73235. if (!scene) {
  73236. return;
  73237. }
  73238. var engine = this._engine;
  73239. // Render
  73240. engine.enableEffect(this._effect);
  73241. engine.setState(false);
  73242. // Texture
  73243. for (var name in this._textures) {
  73244. this._effect.setTexture(name, this._textures[name]);
  73245. }
  73246. // Float
  73247. for (name in this._ints) {
  73248. this._effect.setInt(name, this._ints[name]);
  73249. }
  73250. // Float
  73251. for (name in this._floats) {
  73252. this._effect.setFloat(name, this._floats[name]);
  73253. }
  73254. // Floats
  73255. for (name in this._floatsArrays) {
  73256. this._effect.setArray(name, this._floatsArrays[name]);
  73257. }
  73258. // Color3
  73259. for (name in this._colors3) {
  73260. this._effect.setColor3(name, this._colors3[name]);
  73261. }
  73262. // Color4
  73263. for (name in this._colors4) {
  73264. var color = this._colors4[name];
  73265. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73266. }
  73267. // Vector2
  73268. for (name in this._vectors2) {
  73269. this._effect.setVector2(name, this._vectors2[name]);
  73270. }
  73271. // Vector3
  73272. for (name in this._vectors3) {
  73273. this._effect.setVector3(name, this._vectors3[name]);
  73274. }
  73275. // Matrix
  73276. for (name in this._matrices) {
  73277. this._effect.setMatrix(name, this._matrices[name]);
  73278. }
  73279. if (!this._texture) {
  73280. return;
  73281. }
  73282. if (this.isCube) {
  73283. for (var face = 0; face < 6; face++) {
  73284. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73285. // VBOs
  73286. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73287. this._effect.setFloat("face", face);
  73288. // Clear
  73289. engine.clear(scene.clearColor, true, true, true);
  73290. // Draw order
  73291. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73292. // Mipmaps
  73293. if (face === 5) {
  73294. engine.generateMipMapsForCubemap(this._texture);
  73295. }
  73296. }
  73297. }
  73298. else {
  73299. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73300. // VBOs
  73301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73302. // Clear
  73303. engine.clear(scene.clearColor, true, true, true);
  73304. // Draw order
  73305. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73306. }
  73307. // Unbind
  73308. engine.unBindFramebuffer(this._texture, this.isCube);
  73309. if (this.onGenerated) {
  73310. this.onGenerated();
  73311. }
  73312. };
  73313. ProceduralTexture.prototype.clone = function () {
  73314. var textureSize = this.getSize();
  73315. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73316. // Base texture
  73317. newTexture.hasAlpha = this.hasAlpha;
  73318. newTexture.level = this.level;
  73319. // RenderTarget Texture
  73320. newTexture.coordinatesMode = this.coordinatesMode;
  73321. return newTexture;
  73322. };
  73323. ProceduralTexture.prototype.dispose = function () {
  73324. var scene = this.getScene();
  73325. if (!scene) {
  73326. return;
  73327. }
  73328. var index = scene.proceduralTextures.indexOf(this);
  73329. if (index >= 0) {
  73330. scene.proceduralTextures.splice(index, 1);
  73331. }
  73332. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73333. if (vertexBuffer) {
  73334. vertexBuffer.dispose();
  73335. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73336. }
  73337. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73338. this._indexBuffer = null;
  73339. }
  73340. _super.prototype.dispose.call(this);
  73341. };
  73342. __decorate([
  73343. BABYLON.serialize()
  73344. ], ProceduralTexture.prototype, "_size", void 0);
  73345. __decorate([
  73346. BABYLON.serialize()
  73347. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73348. __decorate([
  73349. BABYLON.serialize()
  73350. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73351. __decorate([
  73352. BABYLON.serialize()
  73353. ], ProceduralTexture.prototype, "refreshRate", null);
  73354. return ProceduralTexture;
  73355. }(BABYLON.Texture));
  73356. BABYLON.ProceduralTexture = ProceduralTexture;
  73357. })(BABYLON || (BABYLON = {}));
  73358. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73359. var BABYLON;
  73360. (function (BABYLON) {
  73361. var CustomProceduralTexture = /** @class */ (function (_super) {
  73362. __extends(CustomProceduralTexture, _super);
  73363. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73364. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73365. _this._animate = true;
  73366. _this._time = 0;
  73367. _this._texturePath = texturePath;
  73368. //Try to load json
  73369. _this.loadJson(texturePath);
  73370. _this.refreshRate = 1;
  73371. return _this;
  73372. }
  73373. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73374. var _this = this;
  73375. var noConfigFile = function () {
  73376. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73377. try {
  73378. _this.setFragment(_this._texturePath);
  73379. }
  73380. catch (ex) {
  73381. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73382. }
  73383. };
  73384. var configFileUrl = jsonUrl + "/config.json";
  73385. var xhr = new XMLHttpRequest();
  73386. xhr.open("GET", configFileUrl, true);
  73387. xhr.addEventListener("load", function () {
  73388. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73389. try {
  73390. _this._config = JSON.parse(xhr.response);
  73391. _this.updateShaderUniforms();
  73392. _this.updateTextures();
  73393. _this.setFragment(_this._texturePath + "/custom");
  73394. _this._animate = _this._config.animate;
  73395. _this.refreshRate = _this._config.refreshrate;
  73396. }
  73397. catch (ex) {
  73398. noConfigFile();
  73399. }
  73400. }
  73401. else {
  73402. noConfigFile();
  73403. }
  73404. }, false);
  73405. xhr.addEventListener("error", function () {
  73406. noConfigFile();
  73407. }, false);
  73408. try {
  73409. xhr.send();
  73410. }
  73411. catch (ex) {
  73412. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  73413. }
  73414. };
  73415. CustomProceduralTexture.prototype.isReady = function () {
  73416. if (!_super.prototype.isReady.call(this)) {
  73417. return false;
  73418. }
  73419. for (var name in this._textures) {
  73420. var texture = this._textures[name];
  73421. if (!texture.isReady()) {
  73422. return false;
  73423. }
  73424. }
  73425. return true;
  73426. };
  73427. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73428. var scene = this.getScene();
  73429. if (this._animate && scene) {
  73430. this._time += scene.getAnimationRatio() * 0.03;
  73431. this.updateShaderUniforms();
  73432. }
  73433. _super.prototype.render.call(this, useCameraPostProcess);
  73434. };
  73435. CustomProceduralTexture.prototype.updateTextures = function () {
  73436. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  73437. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  73438. }
  73439. };
  73440. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  73441. if (this._config) {
  73442. for (var j = 0; j < this._config.uniforms.length; j++) {
  73443. var uniform = this._config.uniforms[j];
  73444. switch (uniform.type) {
  73445. case "float":
  73446. this.setFloat(uniform.name, uniform.value);
  73447. break;
  73448. case "color3":
  73449. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  73450. break;
  73451. case "color4":
  73452. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  73453. break;
  73454. case "vector2":
  73455. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  73456. break;
  73457. case "vector3":
  73458. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  73459. break;
  73460. }
  73461. }
  73462. }
  73463. this.setFloat("time", this._time);
  73464. };
  73465. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  73466. get: function () {
  73467. return this._animate;
  73468. },
  73469. set: function (value) {
  73470. this._animate = value;
  73471. },
  73472. enumerable: true,
  73473. configurable: true
  73474. });
  73475. return CustomProceduralTexture;
  73476. }(BABYLON.ProceduralTexture));
  73477. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  73478. })(BABYLON || (BABYLON = {}));
  73479. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  73480. var BABYLON;
  73481. (function (BABYLON) {
  73482. var FreeCameraGamepadInput = /** @class */ (function () {
  73483. function FreeCameraGamepadInput() {
  73484. this.gamepadAngularSensibility = 200;
  73485. this.gamepadMoveSensibility = 40;
  73486. // private members
  73487. this._cameraTransform = BABYLON.Matrix.Identity();
  73488. this._deltaTransform = BABYLON.Vector3.Zero();
  73489. this._vector3 = BABYLON.Vector3.Zero();
  73490. this._vector2 = BABYLON.Vector2.Zero();
  73491. }
  73492. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73493. var _this = this;
  73494. var manager = this.camera.getScene().gamepadManager;
  73495. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73496. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73497. // prioritize XBOX gamepads.
  73498. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73499. _this.gamepad = gamepad;
  73500. }
  73501. }
  73502. });
  73503. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73504. if (_this.gamepad === gamepad) {
  73505. _this.gamepad = null;
  73506. }
  73507. });
  73508. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73509. };
  73510. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  73511. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73512. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73513. this.gamepad = null;
  73514. };
  73515. FreeCameraGamepadInput.prototype.checkInputs = function () {
  73516. if (this.gamepad && this.gamepad.leftStick) {
  73517. var camera = this.camera;
  73518. var LSValues = this.gamepad.leftStick;
  73519. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  73520. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73521. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  73522. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  73523. var RSValues = this.gamepad.rightStick;
  73524. if (RSValues) {
  73525. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  73526. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  73527. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  73528. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  73529. }
  73530. else {
  73531. RSValues = { x: 0, y: 0 };
  73532. }
  73533. if (!camera.rotationQuaternion) {
  73534. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  73535. }
  73536. else {
  73537. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  73538. }
  73539. var speed = camera._computeLocalCameraSpeed() * 50.0;
  73540. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  73541. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  73542. camera.cameraDirection.addInPlace(this._deltaTransform);
  73543. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  73544. camera.cameraRotation.addInPlace(this._vector2);
  73545. }
  73546. };
  73547. FreeCameraGamepadInput.prototype.getClassName = function () {
  73548. return "FreeCameraGamepadInput";
  73549. };
  73550. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  73551. return "gamepad";
  73552. };
  73553. __decorate([
  73554. BABYLON.serialize()
  73555. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  73556. __decorate([
  73557. BABYLON.serialize()
  73558. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73559. return FreeCameraGamepadInput;
  73560. }());
  73561. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  73562. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  73563. })(BABYLON || (BABYLON = {}));
  73564. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  73565. var BABYLON;
  73566. (function (BABYLON) {
  73567. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  73568. function ArcRotateCameraGamepadInput() {
  73569. this.gamepadRotationSensibility = 80;
  73570. this.gamepadMoveSensibility = 40;
  73571. }
  73572. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73573. var _this = this;
  73574. var manager = this.camera.getScene().gamepadManager;
  73575. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73576. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73577. // prioritize XBOX gamepads.
  73578. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73579. _this.gamepad = gamepad;
  73580. }
  73581. }
  73582. });
  73583. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73584. if (_this.gamepad === gamepad) {
  73585. _this.gamepad = null;
  73586. }
  73587. });
  73588. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73589. };
  73590. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73591. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73592. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73593. this.gamepad = null;
  73594. };
  73595. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73596. if (this.gamepad) {
  73597. var camera = this.camera;
  73598. var RSValues = this.gamepad.rightStick;
  73599. if (RSValues) {
  73600. if (RSValues.x != 0) {
  73601. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73602. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73603. camera.inertialAlphaOffset += normalizedRX;
  73604. }
  73605. }
  73606. if (RSValues.y != 0) {
  73607. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73608. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73609. camera.inertialBetaOffset += normalizedRY;
  73610. }
  73611. }
  73612. }
  73613. var LSValues = this.gamepad.leftStick;
  73614. if (LSValues && LSValues.y != 0) {
  73615. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73616. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73617. this.camera.inertialRadiusOffset -= normalizedLY;
  73618. }
  73619. }
  73620. }
  73621. };
  73622. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73623. return "ArcRotateCameraGamepadInput";
  73624. };
  73625. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73626. return "gamepad";
  73627. };
  73628. __decorate([
  73629. BABYLON.serialize()
  73630. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73631. __decorate([
  73632. BABYLON.serialize()
  73633. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73634. return ArcRotateCameraGamepadInput;
  73635. }());
  73636. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73637. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73638. })(BABYLON || (BABYLON = {}));
  73639. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73640. var BABYLON;
  73641. (function (BABYLON) {
  73642. var GamepadManager = /** @class */ (function () {
  73643. function GamepadManager(_scene) {
  73644. var _this = this;
  73645. this._scene = _scene;
  73646. this._babylonGamepads = [];
  73647. this._oneGamepadConnected = false;
  73648. /** @hidden */
  73649. this._isMonitoring = false;
  73650. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73651. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73652. this._gamepadEventSupported = false;
  73653. }
  73654. else {
  73655. this._gamepadEventSupported = 'GamepadEvent' in window;
  73656. this._gamepadSupport = (navigator.getGamepads ||
  73657. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73658. }
  73659. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73660. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73661. for (var i in _this._babylonGamepads) {
  73662. var gamepad = _this._babylonGamepads[i];
  73663. if (gamepad && gamepad._isConnected) {
  73664. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73665. }
  73666. }
  73667. });
  73668. this._onGamepadConnectedEvent = function (evt) {
  73669. var gamepad = evt.gamepad;
  73670. if (gamepad.index in _this._babylonGamepads) {
  73671. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73672. return;
  73673. }
  73674. }
  73675. var newGamepad;
  73676. if (_this._babylonGamepads[gamepad.index]) {
  73677. newGamepad = _this._babylonGamepads[gamepad.index];
  73678. newGamepad.browserGamepad = gamepad;
  73679. newGamepad._isConnected = true;
  73680. }
  73681. else {
  73682. newGamepad = _this._addNewGamepad(gamepad);
  73683. }
  73684. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73685. _this._startMonitoringGamepads();
  73686. };
  73687. this._onGamepadDisconnectedEvent = function (evt) {
  73688. var gamepad = evt.gamepad;
  73689. // Remove the gamepad from the list of gamepads to monitor.
  73690. for (var i in _this._babylonGamepads) {
  73691. if (_this._babylonGamepads[i].index === gamepad.index) {
  73692. var disconnectedGamepad = _this._babylonGamepads[i];
  73693. disconnectedGamepad._isConnected = false;
  73694. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73695. break;
  73696. }
  73697. }
  73698. };
  73699. if (this._gamepadSupport) {
  73700. //first add already-connected gamepads
  73701. this._updateGamepadObjects();
  73702. if (this._babylonGamepads.length) {
  73703. this._startMonitoringGamepads();
  73704. }
  73705. // Checking if the gamepad connected event is supported (like in Firefox)
  73706. if (this._gamepadEventSupported) {
  73707. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73708. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73709. }
  73710. else {
  73711. this._startMonitoringGamepads();
  73712. }
  73713. }
  73714. }
  73715. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73716. get: function () {
  73717. return this._babylonGamepads;
  73718. },
  73719. enumerable: true,
  73720. configurable: true
  73721. });
  73722. GamepadManager.prototype.getGamepadByType = function (type) {
  73723. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73724. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73725. var gamepad = _a[_i];
  73726. if (gamepad && gamepad.type === type) {
  73727. return gamepad;
  73728. }
  73729. }
  73730. return null;
  73731. };
  73732. GamepadManager.prototype.dispose = function () {
  73733. if (this._gamepadEventSupported) {
  73734. if (this._onGamepadConnectedEvent) {
  73735. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73736. }
  73737. if (this._onGamepadDisconnectedEvent) {
  73738. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73739. }
  73740. this._onGamepadConnectedEvent = null;
  73741. this._onGamepadDisconnectedEvent = null;
  73742. }
  73743. this._babylonGamepads.forEach(function (gamepad) {
  73744. gamepad.dispose();
  73745. });
  73746. this.onGamepadConnectedObservable.clear();
  73747. this.onGamepadDisconnectedObservable.clear();
  73748. this._oneGamepadConnected = false;
  73749. this._stopMonitoringGamepads();
  73750. this._babylonGamepads = [];
  73751. };
  73752. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73753. if (!this._oneGamepadConnected) {
  73754. this._oneGamepadConnected = true;
  73755. }
  73756. var newGamepad;
  73757. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73758. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73759. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73760. }
  73761. // if pose is supported, use the (WebVR) pose enabled controller
  73762. else if (gamepad.pose) {
  73763. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73764. }
  73765. else {
  73766. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73767. }
  73768. this._babylonGamepads[newGamepad.index] = newGamepad;
  73769. return newGamepad;
  73770. };
  73771. GamepadManager.prototype._startMonitoringGamepads = function () {
  73772. if (!this._isMonitoring) {
  73773. this._isMonitoring = true;
  73774. //back-comp
  73775. if (!this._scene) {
  73776. this._checkGamepadsStatus();
  73777. }
  73778. }
  73779. };
  73780. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73781. this._isMonitoring = false;
  73782. };
  73783. /** @hidden */
  73784. GamepadManager.prototype._checkGamepadsStatus = function () {
  73785. var _this = this;
  73786. // Hack to be compatible Chrome
  73787. this._updateGamepadObjects();
  73788. for (var i in this._babylonGamepads) {
  73789. var gamepad = this._babylonGamepads[i];
  73790. if (!gamepad || !gamepad.isConnected) {
  73791. continue;
  73792. }
  73793. gamepad.update();
  73794. }
  73795. if (this._isMonitoring && !this._scene) {
  73796. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73797. }
  73798. };
  73799. // This function is called only on Chrome, which does not properly support
  73800. // connection/disconnection events and forces you to recopy again the gamepad object
  73801. GamepadManager.prototype._updateGamepadObjects = function () {
  73802. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73803. for (var i = 0; i < gamepads.length; i++) {
  73804. var gamepad = gamepads[i];
  73805. if (gamepad) {
  73806. if (!this._babylonGamepads[gamepad.index]) {
  73807. var newGamepad = this._addNewGamepad(gamepad);
  73808. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73809. }
  73810. else {
  73811. // Forced to copy again this object for Chrome for unknown reason
  73812. this._babylonGamepads[i].browserGamepad = gamepad;
  73813. if (!this._babylonGamepads[i].isConnected) {
  73814. this._babylonGamepads[i]._isConnected = true;
  73815. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73816. }
  73817. }
  73818. }
  73819. }
  73820. };
  73821. return GamepadManager;
  73822. }());
  73823. BABYLON.GamepadManager = GamepadManager;
  73824. })(BABYLON || (BABYLON = {}));
  73825. //# sourceMappingURL=babylon.gamepadManager.js.map
  73826. var BABYLON;
  73827. (function (BABYLON) {
  73828. var StickValues = /** @class */ (function () {
  73829. function StickValues(x, y) {
  73830. this.x = x;
  73831. this.y = y;
  73832. }
  73833. return StickValues;
  73834. }());
  73835. BABYLON.StickValues = StickValues;
  73836. var Gamepad = /** @class */ (function () {
  73837. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73838. if (leftStickX === void 0) { leftStickX = 0; }
  73839. if (leftStickY === void 0) { leftStickY = 1; }
  73840. if (rightStickX === void 0) { rightStickX = 2; }
  73841. if (rightStickY === void 0) { rightStickY = 3; }
  73842. this.id = id;
  73843. this.index = index;
  73844. this.browserGamepad = browserGamepad;
  73845. this._leftStick = { x: 0, y: 0 };
  73846. this._rightStick = { x: 0, y: 0 };
  73847. /** @hidden */
  73848. this._isConnected = true;
  73849. this._invertLeftStickY = false;
  73850. this.type = Gamepad.GAMEPAD;
  73851. this._leftStickAxisX = leftStickX;
  73852. this._leftStickAxisY = leftStickY;
  73853. this._rightStickAxisX = rightStickX;
  73854. this._rightStickAxisY = rightStickY;
  73855. if (this.browserGamepad.axes.length >= 2) {
  73856. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73857. }
  73858. if (this.browserGamepad.axes.length >= 4) {
  73859. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73860. }
  73861. }
  73862. Object.defineProperty(Gamepad.prototype, "isConnected", {
  73863. get: function () {
  73864. return this._isConnected;
  73865. },
  73866. enumerable: true,
  73867. configurable: true
  73868. });
  73869. Gamepad.prototype.onleftstickchanged = function (callback) {
  73870. this._onleftstickchanged = callback;
  73871. };
  73872. Gamepad.prototype.onrightstickchanged = function (callback) {
  73873. this._onrightstickchanged = callback;
  73874. };
  73875. Object.defineProperty(Gamepad.prototype, "leftStick", {
  73876. get: function () {
  73877. return this._leftStick;
  73878. },
  73879. set: function (newValues) {
  73880. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  73881. this._onleftstickchanged(newValues);
  73882. }
  73883. this._leftStick = newValues;
  73884. },
  73885. enumerable: true,
  73886. configurable: true
  73887. });
  73888. Object.defineProperty(Gamepad.prototype, "rightStick", {
  73889. get: function () {
  73890. return this._rightStick;
  73891. },
  73892. set: function (newValues) {
  73893. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  73894. this._onrightstickchanged(newValues);
  73895. }
  73896. this._rightStick = newValues;
  73897. },
  73898. enumerable: true,
  73899. configurable: true
  73900. });
  73901. Gamepad.prototype.update = function () {
  73902. if (this._leftStick) {
  73903. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73904. if (this._invertLeftStickY) {
  73905. this.leftStick.y *= -1;
  73906. }
  73907. }
  73908. if (this._rightStick) {
  73909. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73910. }
  73911. };
  73912. Gamepad.prototype.dispose = function () {
  73913. };
  73914. Gamepad.GAMEPAD = 0;
  73915. Gamepad.GENERIC = 1;
  73916. Gamepad.XBOX = 2;
  73917. Gamepad.POSE_ENABLED = 3;
  73918. return Gamepad;
  73919. }());
  73920. BABYLON.Gamepad = Gamepad;
  73921. var GenericPad = /** @class */ (function (_super) {
  73922. __extends(GenericPad, _super);
  73923. function GenericPad(id, index, browserGamepad) {
  73924. var _this = _super.call(this, id, index, browserGamepad) || this;
  73925. _this.onButtonDownObservable = new BABYLON.Observable();
  73926. _this.onButtonUpObservable = new BABYLON.Observable();
  73927. _this.type = Gamepad.GENERIC;
  73928. _this._buttons = new Array(browserGamepad.buttons.length);
  73929. return _this;
  73930. }
  73931. GenericPad.prototype.onbuttondown = function (callback) {
  73932. this._onbuttondown = callback;
  73933. };
  73934. GenericPad.prototype.onbuttonup = function (callback) {
  73935. this._onbuttonup = callback;
  73936. };
  73937. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  73938. if (newValue !== currentValue) {
  73939. if (newValue === 1) {
  73940. if (this._onbuttondown) {
  73941. this._onbuttondown(buttonIndex);
  73942. }
  73943. this.onButtonDownObservable.notifyObservers(buttonIndex);
  73944. }
  73945. if (newValue === 0) {
  73946. if (this._onbuttonup) {
  73947. this._onbuttonup(buttonIndex);
  73948. }
  73949. this.onButtonUpObservable.notifyObservers(buttonIndex);
  73950. }
  73951. }
  73952. return newValue;
  73953. };
  73954. GenericPad.prototype.update = function () {
  73955. _super.prototype.update.call(this);
  73956. for (var index = 0; index < this._buttons.length; index++) {
  73957. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  73958. }
  73959. };
  73960. GenericPad.prototype.dispose = function () {
  73961. _super.prototype.dispose.call(this);
  73962. this.onButtonDownObservable.clear();
  73963. this.onButtonUpObservable.clear();
  73964. };
  73965. return GenericPad;
  73966. }(Gamepad));
  73967. BABYLON.GenericPad = GenericPad;
  73968. })(BABYLON || (BABYLON = {}));
  73969. //# sourceMappingURL=babylon.gamepad.js.map
  73970. var BABYLON;
  73971. (function (BABYLON) {
  73972. /**
  73973. * Defines supported buttons for XBox360 compatible gamepads
  73974. */
  73975. var Xbox360Button;
  73976. (function (Xbox360Button) {
  73977. /** A */
  73978. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73979. /** B */
  73980. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73981. /** X */
  73982. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73983. /** Y */
  73984. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73985. /** Start */
  73986. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73987. /** Back */
  73988. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73989. /** Left button */
  73990. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73991. /** Right button */
  73992. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73993. /** Left stick */
  73994. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73995. /** Right stick */
  73996. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73997. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73998. /** Defines values for XBox360 DPad */
  73999. var Xbox360Dpad;
  74000. (function (Xbox360Dpad) {
  74001. /** Up */
  74002. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  74003. /** Down */
  74004. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  74005. /** Left */
  74006. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  74007. /** Right */
  74008. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  74009. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  74010. /**
  74011. * Defines a XBox360 gamepad
  74012. */
  74013. var Xbox360Pad = /** @class */ (function (_super) {
  74014. __extends(Xbox360Pad, _super);
  74015. /**
  74016. * Creates a new XBox360 gamepad object
  74017. * @param id defines the id of this gamepad
  74018. * @param index defines its index
  74019. * @param gamepad defines the internal HTML gamepad object
  74020. * @param xboxOne defines if it is a XBox One gamepad
  74021. */
  74022. function Xbox360Pad(id, index, gamepad, xboxOne) {
  74023. if (xboxOne === void 0) { xboxOne = false; }
  74024. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  74025. _this._leftTrigger = 0;
  74026. _this._rightTrigger = 0;
  74027. /** Observable raised when a button is pressed */
  74028. _this.onButtonDownObservable = new BABYLON.Observable();
  74029. /** Observable raised when a button is released */
  74030. _this.onButtonUpObservable = new BABYLON.Observable();
  74031. /** Observable raised when a pad is pressed */
  74032. _this.onPadDownObservable = new BABYLON.Observable();
  74033. /** Observable raised when a pad is released */
  74034. _this.onPadUpObservable = new BABYLON.Observable();
  74035. _this._buttonA = 0;
  74036. _this._buttonB = 0;
  74037. _this._buttonX = 0;
  74038. _this._buttonY = 0;
  74039. _this._buttonBack = 0;
  74040. _this._buttonStart = 0;
  74041. _this._buttonLB = 0;
  74042. _this._buttonRB = 0;
  74043. _this._buttonLeftStick = 0;
  74044. _this._buttonRightStick = 0;
  74045. _this._dPadUp = 0;
  74046. _this._dPadDown = 0;
  74047. _this._dPadLeft = 0;
  74048. _this._dPadRight = 0;
  74049. _this._isXboxOnePad = false;
  74050. _this.type = BABYLON.Gamepad.XBOX;
  74051. _this._isXboxOnePad = xboxOne;
  74052. return _this;
  74053. }
  74054. /**
  74055. * Defines the callback to call when left trigger is pressed
  74056. * @param callback defines the callback to use
  74057. */
  74058. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  74059. this._onlefttriggerchanged = callback;
  74060. };
  74061. /**
  74062. * Defines the callback to call when right trigger is pressed
  74063. * @param callback defines the callback to use
  74064. */
  74065. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  74066. this._onrighttriggerchanged = callback;
  74067. };
  74068. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  74069. /**
  74070. * Gets or sets left trigger value
  74071. */
  74072. get: function () {
  74073. return this._leftTrigger;
  74074. },
  74075. set: function (newValue) {
  74076. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  74077. this._onlefttriggerchanged(newValue);
  74078. }
  74079. this._leftTrigger = newValue;
  74080. },
  74081. enumerable: true,
  74082. configurable: true
  74083. });
  74084. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  74085. /**
  74086. * Gets or sets right trigger value
  74087. */
  74088. get: function () {
  74089. return this._rightTrigger;
  74090. },
  74091. set: function (newValue) {
  74092. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  74093. this._onrighttriggerchanged(newValue);
  74094. }
  74095. this._rightTrigger = newValue;
  74096. },
  74097. enumerable: true,
  74098. configurable: true
  74099. });
  74100. /**
  74101. * Defines the callback to call when a button is pressed
  74102. * @param callback defines the callback to use
  74103. */
  74104. Xbox360Pad.prototype.onbuttondown = function (callback) {
  74105. this._onbuttondown = callback;
  74106. };
  74107. /**
  74108. * Defines the callback to call when a button is released
  74109. * @param callback defines the callback to use
  74110. */
  74111. Xbox360Pad.prototype.onbuttonup = function (callback) {
  74112. this._onbuttonup = callback;
  74113. };
  74114. /**
  74115. * Defines the callback to call when a pad is pressed
  74116. * @param callback defines the callback to use
  74117. */
  74118. Xbox360Pad.prototype.ondpaddown = function (callback) {
  74119. this._ondpaddown = callback;
  74120. };
  74121. /**
  74122. * Defines the callback to call when a pad is released
  74123. * @param callback defines the callback to use
  74124. */
  74125. Xbox360Pad.prototype.ondpadup = function (callback) {
  74126. this._ondpadup = callback;
  74127. };
  74128. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  74129. if (newValue !== currentValue) {
  74130. if (newValue === 1) {
  74131. if (this._onbuttondown) {
  74132. this._onbuttondown(buttonType);
  74133. }
  74134. this.onButtonDownObservable.notifyObservers(buttonType);
  74135. }
  74136. if (newValue === 0) {
  74137. if (this._onbuttonup) {
  74138. this._onbuttonup(buttonType);
  74139. }
  74140. this.onButtonUpObservable.notifyObservers(buttonType);
  74141. }
  74142. }
  74143. return newValue;
  74144. };
  74145. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  74146. if (newValue !== currentValue) {
  74147. if (newValue === 1) {
  74148. if (this._ondpaddown) {
  74149. this._ondpaddown(buttonType);
  74150. }
  74151. this.onPadDownObservable.notifyObservers(buttonType);
  74152. }
  74153. if (newValue === 0) {
  74154. if (this._ondpadup) {
  74155. this._ondpadup(buttonType);
  74156. }
  74157. this.onPadUpObservable.notifyObservers(buttonType);
  74158. }
  74159. }
  74160. return newValue;
  74161. };
  74162. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  74163. /** Gets or sets value of A button */
  74164. get: function () {
  74165. return this._buttonA;
  74166. },
  74167. set: function (value) {
  74168. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  74169. },
  74170. enumerable: true,
  74171. configurable: true
  74172. });
  74173. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  74174. /** Gets or sets value of B button */
  74175. get: function () {
  74176. return this._buttonB;
  74177. },
  74178. set: function (value) {
  74179. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  74180. },
  74181. enumerable: true,
  74182. configurable: true
  74183. });
  74184. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  74185. /** Gets or sets value of X button */
  74186. get: function () {
  74187. return this._buttonX;
  74188. },
  74189. set: function (value) {
  74190. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  74191. },
  74192. enumerable: true,
  74193. configurable: true
  74194. });
  74195. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  74196. /** Gets or sets value of Y button */
  74197. get: function () {
  74198. return this._buttonY;
  74199. },
  74200. set: function (value) {
  74201. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  74202. },
  74203. enumerable: true,
  74204. configurable: true
  74205. });
  74206. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  74207. /** Gets or sets value of Start button */
  74208. get: function () {
  74209. return this._buttonStart;
  74210. },
  74211. set: function (value) {
  74212. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  74213. },
  74214. enumerable: true,
  74215. configurable: true
  74216. });
  74217. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  74218. /** Gets or sets value of Back button */
  74219. get: function () {
  74220. return this._buttonBack;
  74221. },
  74222. set: function (value) {
  74223. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  74224. },
  74225. enumerable: true,
  74226. configurable: true
  74227. });
  74228. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  74229. /** Gets or sets value of Left button */
  74230. get: function () {
  74231. return this._buttonLB;
  74232. },
  74233. set: function (value) {
  74234. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  74235. },
  74236. enumerable: true,
  74237. configurable: true
  74238. });
  74239. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  74240. /** Gets or sets value of Right button */
  74241. get: function () {
  74242. return this._buttonRB;
  74243. },
  74244. set: function (value) {
  74245. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  74246. },
  74247. enumerable: true,
  74248. configurable: true
  74249. });
  74250. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  74251. /** Gets or sets value of left stick */
  74252. get: function () {
  74253. return this._buttonLeftStick;
  74254. },
  74255. set: function (value) {
  74256. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  74257. },
  74258. enumerable: true,
  74259. configurable: true
  74260. });
  74261. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74262. /** Gets or sets value of right stick */
  74263. get: function () {
  74264. return this._buttonRightStick;
  74265. },
  74266. set: function (value) {
  74267. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74268. },
  74269. enumerable: true,
  74270. configurable: true
  74271. });
  74272. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74273. /** Gets or sets value of DPad up */
  74274. get: function () {
  74275. return this._dPadUp;
  74276. },
  74277. set: function (value) {
  74278. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74279. },
  74280. enumerable: true,
  74281. configurable: true
  74282. });
  74283. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74284. /** Gets or sets value of DPad down */
  74285. get: function () {
  74286. return this._dPadDown;
  74287. },
  74288. set: function (value) {
  74289. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74290. },
  74291. enumerable: true,
  74292. configurable: true
  74293. });
  74294. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74295. /** Gets or sets value of DPad left */
  74296. get: function () {
  74297. return this._dPadLeft;
  74298. },
  74299. set: function (value) {
  74300. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74301. },
  74302. enumerable: true,
  74303. configurable: true
  74304. });
  74305. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74306. /** Gets or sets value of DPad right */
  74307. get: function () {
  74308. return this._dPadRight;
  74309. },
  74310. set: function (value) {
  74311. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74312. },
  74313. enumerable: true,
  74314. configurable: true
  74315. });
  74316. /**
  74317. * Force the gamepad to synchronize with device values
  74318. */
  74319. Xbox360Pad.prototype.update = function () {
  74320. _super.prototype.update.call(this);
  74321. if (this._isXboxOnePad) {
  74322. this.buttonA = this.browserGamepad.buttons[0].value;
  74323. this.buttonB = this.browserGamepad.buttons[1].value;
  74324. this.buttonX = this.browserGamepad.buttons[2].value;
  74325. this.buttonY = this.browserGamepad.buttons[3].value;
  74326. this.buttonLB = this.browserGamepad.buttons[4].value;
  74327. this.buttonRB = this.browserGamepad.buttons[5].value;
  74328. this.leftTrigger = this.browserGamepad.axes[2];
  74329. this.rightTrigger = this.browserGamepad.axes[5];
  74330. this.buttonBack = this.browserGamepad.buttons[9].value;
  74331. this.buttonStart = this.browserGamepad.buttons[8].value;
  74332. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74333. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74334. this.dPadUp = this.browserGamepad.buttons[11].value;
  74335. this.dPadDown = this.browserGamepad.buttons[12].value;
  74336. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74337. this.dPadRight = this.browserGamepad.buttons[14].value;
  74338. }
  74339. else {
  74340. this.buttonA = this.browserGamepad.buttons[0].value;
  74341. this.buttonB = this.browserGamepad.buttons[1].value;
  74342. this.buttonX = this.browserGamepad.buttons[2].value;
  74343. this.buttonY = this.browserGamepad.buttons[3].value;
  74344. this.buttonLB = this.browserGamepad.buttons[4].value;
  74345. this.buttonRB = this.browserGamepad.buttons[5].value;
  74346. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74347. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74348. this.buttonBack = this.browserGamepad.buttons[8].value;
  74349. this.buttonStart = this.browserGamepad.buttons[9].value;
  74350. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74351. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74352. this.dPadUp = this.browserGamepad.buttons[12].value;
  74353. this.dPadDown = this.browserGamepad.buttons[13].value;
  74354. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74355. this.dPadRight = this.browserGamepad.buttons[15].value;
  74356. }
  74357. };
  74358. Xbox360Pad.prototype.dispose = function () {
  74359. _super.prototype.dispose.call(this);
  74360. this.onButtonDownObservable.clear();
  74361. this.onButtonUpObservable.clear();
  74362. this.onPadDownObservable.clear();
  74363. this.onPadUpObservable.clear();
  74364. };
  74365. return Xbox360Pad;
  74366. }(BABYLON.Gamepad));
  74367. BABYLON.Xbox360Pad = Xbox360Pad;
  74368. })(BABYLON || (BABYLON = {}));
  74369. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74370. var BABYLON;
  74371. (function (BABYLON) {
  74372. /**
  74373. * Defines the types of pose enabled controllers that are supported
  74374. */
  74375. var PoseEnabledControllerType;
  74376. (function (PoseEnabledControllerType) {
  74377. /**
  74378. * HTC Vive
  74379. */
  74380. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74381. /**
  74382. * Oculus Rift
  74383. */
  74384. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74385. /**
  74386. * Windows mixed reality
  74387. */
  74388. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74389. /**
  74390. * Samsung gear VR
  74391. */
  74392. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  74393. /**
  74394. * Google Daydream
  74395. */
  74396. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  74397. /**
  74398. * Generic
  74399. */
  74400. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  74401. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  74402. /**
  74403. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74404. */
  74405. var PoseEnabledControllerHelper = /** @class */ (function () {
  74406. function PoseEnabledControllerHelper() {
  74407. }
  74408. /**
  74409. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74410. * @param vrGamepad the gamepad to initialized
  74411. * @returns a vr controller of the type the gamepad identified as
  74412. */
  74413. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  74414. // Oculus Touch
  74415. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  74416. return new BABYLON.OculusTouchController(vrGamepad);
  74417. }
  74418. // Windows Mixed Reality controllers
  74419. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  74420. return new BABYLON.WindowsMotionController(vrGamepad);
  74421. }
  74422. // HTC Vive
  74423. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  74424. return new BABYLON.ViveController(vrGamepad);
  74425. }
  74426. // Samsung/Oculus Gear VR or Oculus Go
  74427. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  74428. return new BABYLON.GearVRController(vrGamepad);
  74429. }
  74430. // Google Daydream
  74431. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  74432. return new BABYLON.DaydreamController(vrGamepad);
  74433. }
  74434. // Generic
  74435. else {
  74436. return new BABYLON.GenericController(vrGamepad);
  74437. }
  74438. };
  74439. return PoseEnabledControllerHelper;
  74440. }());
  74441. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  74442. /**
  74443. * Defines the PoseEnabledController object that contains state of a vr capable controller
  74444. */
  74445. var PoseEnabledController = /** @class */ (function (_super) {
  74446. __extends(PoseEnabledController, _super);
  74447. /**
  74448. * Creates a new PoseEnabledController from a gamepad
  74449. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  74450. */
  74451. function PoseEnabledController(browserGamepad) {
  74452. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  74453. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74454. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74455. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  74456. /**
  74457. * The device position in babylon space
  74458. */
  74459. _this.devicePosition = BABYLON.Vector3.Zero();
  74460. /**
  74461. * The device rotation in babylon space
  74462. */
  74463. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  74464. /**
  74465. * The scale factor of the device in babylon space
  74466. */
  74467. _this.deviceScaleFactor = 1;
  74468. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  74469. /**
  74470. * Internal, matrix used to convert room space to babylon space
  74471. * @hidden
  74472. */
  74473. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74474. /**
  74475. * Node to be used when casting a ray from the controller
  74476. * @hidden
  74477. */
  74478. _this._pointingPoseNode = null;
  74479. _this._workingMatrix = BABYLON.Matrix.Identity();
  74480. /**
  74481. * @hidden
  74482. */
  74483. _this._meshAttachedObservable = new BABYLON.Observable();
  74484. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  74485. _this.controllerType = PoseEnabledControllerType.GENERIC;
  74486. _this.position = BABYLON.Vector3.Zero();
  74487. _this.rotationQuaternion = new BABYLON.Quaternion();
  74488. _this._calculatedPosition = BABYLON.Vector3.Zero();
  74489. _this._calculatedRotation = new BABYLON.Quaternion();
  74490. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  74491. return _this;
  74492. }
  74493. /**
  74494. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  74495. */
  74496. PoseEnabledController.prototype.update = function () {
  74497. _super.prototype.update.call(this);
  74498. this._updatePoseAndMesh();
  74499. };
  74500. /**
  74501. * Updates only the pose device and mesh without doing any button event checking
  74502. */
  74503. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  74504. var pose = this.browserGamepad.pose;
  74505. this.updateFromDevice(pose);
  74506. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  74507. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  74508. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74509. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  74510. if (this._mesh) {
  74511. this._mesh.position.copyFrom(this.devicePosition);
  74512. if (this._mesh.rotationQuaternion) {
  74513. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  74514. }
  74515. }
  74516. };
  74517. /**
  74518. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74519. * @param poseData raw pose fromthe device
  74520. */
  74521. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  74522. if (poseData) {
  74523. this.rawPose = poseData;
  74524. if (poseData.position) {
  74525. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  74526. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  74527. this._deviceRoomPosition.z *= -1;
  74528. }
  74529. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  74530. this._calculatedPosition.addInPlace(this.position);
  74531. }
  74532. var pose = this.rawPose;
  74533. if (poseData.orientation && pose.orientation) {
  74534. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  74535. if (this._mesh) {
  74536. if (this._mesh.getScene().useRightHandedSystem) {
  74537. this._deviceRoomRotationQuaternion.z *= -1;
  74538. this._deviceRoomRotationQuaternion.w *= -1;
  74539. }
  74540. else {
  74541. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  74542. }
  74543. }
  74544. // if the camera is set, rotate to the camera's rotation
  74545. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  74546. }
  74547. }
  74548. };
  74549. /**
  74550. * Attaches a mesh to the controller
  74551. * @param mesh the mesh to be attached
  74552. */
  74553. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  74554. if (this._mesh) {
  74555. this._mesh.parent = null;
  74556. }
  74557. this._mesh = mesh;
  74558. if (this._poseControlledCamera) {
  74559. this._mesh.parent = this._poseControlledCamera;
  74560. }
  74561. if (!this._mesh.rotationQuaternion) {
  74562. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  74563. }
  74564. // 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
  74565. this._updatePoseAndMesh();
  74566. if (this._pointingPoseNode) {
  74567. var parents = [];
  74568. var obj = this._pointingPoseNode;
  74569. while (obj.parent) {
  74570. parents.push(obj.parent);
  74571. obj = obj.parent;
  74572. }
  74573. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74574. }
  74575. this._meshAttachedObservable.notifyObservers(mesh);
  74576. };
  74577. /**
  74578. * Attaches the controllers mesh to a camera
  74579. * @param camera the camera the mesh should be attached to
  74580. */
  74581. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74582. this._poseControlledCamera = camera;
  74583. if (this._mesh) {
  74584. this._mesh.parent = this._poseControlledCamera;
  74585. }
  74586. };
  74587. /**
  74588. * Disposes of the controller
  74589. */
  74590. PoseEnabledController.prototype.dispose = function () {
  74591. if (this._mesh) {
  74592. this._mesh.dispose();
  74593. }
  74594. this._mesh = null;
  74595. _super.prototype.dispose.call(this);
  74596. };
  74597. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74598. /**
  74599. * The mesh that is attached to the controller
  74600. */
  74601. get: function () {
  74602. return this._mesh;
  74603. },
  74604. enumerable: true,
  74605. configurable: true
  74606. });
  74607. /**
  74608. * Gets the ray of the controller in the direction the controller is pointing
  74609. * @param length the length the resulting ray should be
  74610. * @returns a ray in the direction the controller is pointing
  74611. */
  74612. PoseEnabledController.prototype.getForwardRay = function (length) {
  74613. if (length === void 0) { length = 100; }
  74614. if (!this.mesh) {
  74615. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74616. }
  74617. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74618. var origin = m.getTranslation();
  74619. var forward = new BABYLON.Vector3(0, 0, -1);
  74620. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74621. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74622. return new BABYLON.Ray(origin, direction, length);
  74623. };
  74624. /**
  74625. * Name of the child mesh that can be used to cast a ray from the controller
  74626. */
  74627. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74628. return PoseEnabledController;
  74629. }(BABYLON.Gamepad));
  74630. BABYLON.PoseEnabledController = PoseEnabledController;
  74631. })(BABYLON || (BABYLON = {}));
  74632. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74633. var BABYLON;
  74634. (function (BABYLON) {
  74635. /**
  74636. * Defines the WebVRController object that represents controllers tracked in 3D space
  74637. */
  74638. var WebVRController = /** @class */ (function (_super) {
  74639. __extends(WebVRController, _super);
  74640. /**
  74641. * Creates a new WebVRController from a gamepad
  74642. * @param vrGamepad the gamepad that the WebVRController should be created from
  74643. */
  74644. function WebVRController(vrGamepad) {
  74645. var _this = _super.call(this, vrGamepad) || this;
  74646. // Observables
  74647. /**
  74648. * Fired when the trigger state has changed
  74649. */
  74650. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74651. /**
  74652. * Fired when the main button state has changed
  74653. */
  74654. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74655. /**
  74656. * Fired when the secondary button state has changed
  74657. */
  74658. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74659. /**
  74660. * Fired when the pad state has changed
  74661. */
  74662. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74663. /**
  74664. * Fired when controllers stick values have changed
  74665. */
  74666. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74667. /**
  74668. * X and Y axis corrisponding to the controllers joystick
  74669. */
  74670. _this.pad = { x: 0, y: 0 };
  74671. // avoid GC, store state in a tmp object
  74672. _this._changes = {
  74673. pressChanged: false,
  74674. touchChanged: false,
  74675. valueChanged: false,
  74676. changed: false
  74677. };
  74678. _this._buttons = new Array(vrGamepad.buttons.length);
  74679. _this.hand = vrGamepad.hand;
  74680. return _this;
  74681. }
  74682. /**
  74683. * Fired when a controller button's state has changed
  74684. * @param callback the callback containing the button that was modified
  74685. */
  74686. WebVRController.prototype.onButtonStateChange = function (callback) {
  74687. this._onButtonStateChange = callback;
  74688. };
  74689. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74690. /**
  74691. * The default controller model for the controller
  74692. */
  74693. get: function () {
  74694. return this._defaultModel;
  74695. },
  74696. enumerable: true,
  74697. configurable: true
  74698. });
  74699. /**
  74700. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74701. */
  74702. WebVRController.prototype.update = function () {
  74703. _super.prototype.update.call(this);
  74704. for (var index = 0; index < this._buttons.length; index++) {
  74705. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74706. }
  74707. ;
  74708. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74709. this.pad.x = this.leftStick.x;
  74710. this.pad.y = this.leftStick.y;
  74711. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74712. }
  74713. };
  74714. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74715. if (!newState) {
  74716. newState = {
  74717. pressed: false,
  74718. touched: false,
  74719. value: 0
  74720. };
  74721. }
  74722. if (!currentState) {
  74723. this._buttons[buttonIndex] = {
  74724. pressed: newState.pressed,
  74725. touched: newState.touched,
  74726. value: newState.value
  74727. };
  74728. return;
  74729. }
  74730. this._checkChanges(newState, currentState);
  74731. if (this._changes.changed) {
  74732. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74733. this._handleButtonChange(buttonIndex, newState, this._changes);
  74734. }
  74735. this._buttons[buttonIndex].pressed = newState.pressed;
  74736. this._buttons[buttonIndex].touched = newState.touched;
  74737. // oculus triggers are never 0, thou not touched.
  74738. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74739. };
  74740. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74741. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74742. this._changes.touchChanged = newState.touched !== currentState.touched;
  74743. this._changes.valueChanged = newState.value !== currentState.value;
  74744. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74745. return this._changes;
  74746. };
  74747. /**
  74748. * Disposes of th webVRCOntroller
  74749. */
  74750. WebVRController.prototype.dispose = function () {
  74751. _super.prototype.dispose.call(this);
  74752. this.onTriggerStateChangedObservable.clear();
  74753. this.onMainButtonStateChangedObservable.clear();
  74754. this.onSecondaryButtonStateChangedObservable.clear();
  74755. this.onPadStateChangedObservable.clear();
  74756. this.onPadValuesChangedObservable.clear();
  74757. };
  74758. return WebVRController;
  74759. }(BABYLON.PoseEnabledController));
  74760. BABYLON.WebVRController = WebVRController;
  74761. })(BABYLON || (BABYLON = {}));
  74762. //# sourceMappingURL=babylon.webVRController.js.map
  74763. var BABYLON;
  74764. (function (BABYLON) {
  74765. /**
  74766. * Oculus Touch Controller
  74767. */
  74768. var OculusTouchController = /** @class */ (function (_super) {
  74769. __extends(OculusTouchController, _super);
  74770. /**
  74771. * Creates a new OculusTouchController from a gamepad
  74772. * @param vrGamepad the gamepad that the controller should be created from
  74773. */
  74774. function OculusTouchController(vrGamepad) {
  74775. var _this = _super.call(this, vrGamepad) || this;
  74776. /**
  74777. * Fired when the secondary trigger on this controller is modified
  74778. */
  74779. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74780. /**
  74781. * Fired when the thumb rest on this controller is modified
  74782. */
  74783. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74784. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74785. return _this;
  74786. }
  74787. /**
  74788. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74789. * @param scene scene in which to add meshes
  74790. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74791. */
  74792. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74793. var _this = this;
  74794. var meshName;
  74795. // Hand
  74796. if (this.hand === 'left') {
  74797. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74798. }
  74799. else { // Right is the default if no hand is specified
  74800. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74801. }
  74802. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74803. /*
  74804. Parent Mesh name: oculus_touch_left
  74805. - body
  74806. - trigger
  74807. - thumbstick
  74808. - grip
  74809. - button_y
  74810. - button_x
  74811. - button_enter
  74812. */
  74813. _this._defaultModel = newMeshes[1];
  74814. _this.attachToMesh(_this._defaultModel);
  74815. if (meshLoaded) {
  74816. meshLoaded(_this._defaultModel);
  74817. }
  74818. });
  74819. };
  74820. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74821. /**
  74822. * Fired when the A button on this controller is modified
  74823. */
  74824. get: function () {
  74825. if (this.hand === 'right') {
  74826. return this.onMainButtonStateChangedObservable;
  74827. }
  74828. else {
  74829. throw new Error('No A button on left hand');
  74830. }
  74831. },
  74832. enumerable: true,
  74833. configurable: true
  74834. });
  74835. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74836. /**
  74837. * Fired when the B button on this controller is modified
  74838. */
  74839. get: function () {
  74840. if (this.hand === 'right') {
  74841. return this.onSecondaryButtonStateChangedObservable;
  74842. }
  74843. else {
  74844. throw new Error('No B button on left hand');
  74845. }
  74846. },
  74847. enumerable: true,
  74848. configurable: true
  74849. });
  74850. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74851. /**
  74852. * Fired when the X button on this controller is modified
  74853. */
  74854. get: function () {
  74855. if (this.hand === 'left') {
  74856. return this.onMainButtonStateChangedObservable;
  74857. }
  74858. else {
  74859. throw new Error('No X button on right hand');
  74860. }
  74861. },
  74862. enumerable: true,
  74863. configurable: true
  74864. });
  74865. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  74866. /**
  74867. * Fired when the Y button on this controller is modified
  74868. */
  74869. get: function () {
  74870. if (this.hand === 'left') {
  74871. return this.onSecondaryButtonStateChangedObservable;
  74872. }
  74873. else {
  74874. throw new Error('No Y button on right hand');
  74875. }
  74876. },
  74877. enumerable: true,
  74878. configurable: true
  74879. });
  74880. /**
  74881. * Called once for each button that changed state since the last frame
  74882. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  74883. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  74884. * 2) secondary trigger (same)
  74885. * 3) A (right) X (left), touch, pressed = value
  74886. * 4) B / Y
  74887. * 5) thumb rest
  74888. * @param buttonIdx Which button index changed
  74889. * @param state New state of the button
  74890. * @param changes Which properties on the state changed since last frame
  74891. */
  74892. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74893. var notifyObject = state; //{ state: state, changes: changes };
  74894. var triggerDirection = this.hand === 'right' ? -1 : 1;
  74895. switch (buttonIdx) {
  74896. case 0:
  74897. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74898. return;
  74899. case 1: // index trigger
  74900. if (this._defaultModel) {
  74901. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  74902. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  74903. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  74904. }
  74905. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74906. return;
  74907. case 2: // secondary trigger
  74908. if (this._defaultModel) {
  74909. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  74910. }
  74911. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  74912. return;
  74913. case 3:
  74914. if (this._defaultModel) {
  74915. if (notifyObject.pressed) {
  74916. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  74917. }
  74918. else {
  74919. (this._defaultModel.getChildren()[1]).position.y = 0;
  74920. }
  74921. }
  74922. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74923. return;
  74924. case 4:
  74925. if (this._defaultModel) {
  74926. if (notifyObject.pressed) {
  74927. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74928. }
  74929. else {
  74930. (this._defaultModel.getChildren()[2]).position.y = 0;
  74931. }
  74932. }
  74933. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74934. return;
  74935. case 5:
  74936. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  74937. return;
  74938. }
  74939. };
  74940. /**
  74941. * Base Url for the controller model.
  74942. */
  74943. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  74944. /**
  74945. * File name for the left controller model.
  74946. */
  74947. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  74948. /**
  74949. * File name for the right controller model.
  74950. */
  74951. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  74952. return OculusTouchController;
  74953. }(BABYLON.WebVRController));
  74954. BABYLON.OculusTouchController = OculusTouchController;
  74955. })(BABYLON || (BABYLON = {}));
  74956. //# sourceMappingURL=babylon.oculusTouchController.js.map
  74957. var BABYLON;
  74958. (function (BABYLON) {
  74959. /**
  74960. * Vive Controller
  74961. */
  74962. var ViveController = /** @class */ (function (_super) {
  74963. __extends(ViveController, _super);
  74964. /**
  74965. * Creates a new ViveController from a gamepad
  74966. * @param vrGamepad the gamepad that the controller should be created from
  74967. */
  74968. function ViveController(vrGamepad) {
  74969. var _this = _super.call(this, vrGamepad) || this;
  74970. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74971. _this._invertLeftStickY = true;
  74972. return _this;
  74973. }
  74974. /**
  74975. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74976. * @param scene scene in which to add meshes
  74977. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74978. */
  74979. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74980. var _this = this;
  74981. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74982. /*
  74983. Parent Mesh name: ViveWand
  74984. - body
  74985. - r_gripper
  74986. - l_gripper
  74987. - menu_button
  74988. - system_button
  74989. - trackpad
  74990. - trigger
  74991. - LED
  74992. */
  74993. _this._defaultModel = newMeshes[1];
  74994. _this.attachToMesh(_this._defaultModel);
  74995. if (meshLoaded) {
  74996. meshLoaded(_this._defaultModel);
  74997. }
  74998. });
  74999. };
  75000. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  75001. /**
  75002. * Fired when the left button on this controller is modified
  75003. */
  75004. get: function () {
  75005. return this.onMainButtonStateChangedObservable;
  75006. },
  75007. enumerable: true,
  75008. configurable: true
  75009. });
  75010. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  75011. /**
  75012. * Fired when the right button on this controller is modified
  75013. */
  75014. get: function () {
  75015. return this.onMainButtonStateChangedObservable;
  75016. },
  75017. enumerable: true,
  75018. configurable: true
  75019. });
  75020. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  75021. /**
  75022. * Fired when the menu button on this controller is modified
  75023. */
  75024. get: function () {
  75025. return this.onSecondaryButtonStateChangedObservable;
  75026. },
  75027. enumerable: true,
  75028. configurable: true
  75029. });
  75030. /**
  75031. * Called once for each button that changed state since the last frame
  75032. * Vive mapping:
  75033. * 0: touchpad
  75034. * 1: trigger
  75035. * 2: left AND right buttons
  75036. * 3: menu button
  75037. * @param buttonIdx Which button index changed
  75038. * @param state New state of the button
  75039. * @param changes Which properties on the state changed since last frame
  75040. */
  75041. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75042. var notifyObject = state; //{ state: state, changes: changes };
  75043. switch (buttonIdx) {
  75044. case 0:
  75045. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75046. return;
  75047. case 1: // index trigger
  75048. if (this._defaultModel) {
  75049. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  75050. }
  75051. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75052. return;
  75053. case 2: // left AND right button
  75054. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75055. return;
  75056. case 3:
  75057. if (this._defaultModel) {
  75058. if (notifyObject.pressed) {
  75059. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75060. }
  75061. else {
  75062. (this._defaultModel.getChildren()[2]).position.y = 0;
  75063. }
  75064. }
  75065. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75066. return;
  75067. }
  75068. };
  75069. /**
  75070. * Base Url for the controller model.
  75071. */
  75072. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  75073. /**
  75074. * File name for the controller model.
  75075. */
  75076. ViveController.MODEL_FILENAME = 'wand.babylon';
  75077. return ViveController;
  75078. }(BABYLON.WebVRController));
  75079. BABYLON.ViveController = ViveController;
  75080. })(BABYLON || (BABYLON = {}));
  75081. //# sourceMappingURL=babylon.viveController.js.map
  75082. var BABYLON;
  75083. (function (BABYLON) {
  75084. /**
  75085. * Generic Controller
  75086. */
  75087. var GenericController = /** @class */ (function (_super) {
  75088. __extends(GenericController, _super);
  75089. /**
  75090. * Creates a new GenericController from a gamepad
  75091. * @param vrGamepad the gamepad that the controller should be created from
  75092. */
  75093. function GenericController(vrGamepad) {
  75094. return _super.call(this, vrGamepad) || this;
  75095. }
  75096. /**
  75097. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75098. * @param scene scene in which to add meshes
  75099. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75100. */
  75101. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75102. var _this = this;
  75103. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  75104. _this._defaultModel = newMeshes[1];
  75105. _this.attachToMesh(_this._defaultModel);
  75106. if (meshLoaded) {
  75107. meshLoaded(_this._defaultModel);
  75108. }
  75109. });
  75110. };
  75111. /**
  75112. * Called once for each button that changed state since the last frame
  75113. * @param buttonIdx Which button index changed
  75114. * @param state New state of the button
  75115. * @param changes Which properties on the state changed since last frame
  75116. */
  75117. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75118. console.log("Button id: " + buttonIdx + "state: ");
  75119. console.dir(state);
  75120. };
  75121. /**
  75122. * Base Url for the controller model.
  75123. */
  75124. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75125. /**
  75126. * File name for the controller model.
  75127. */
  75128. GenericController.MODEL_FILENAME = 'generic.babylon';
  75129. return GenericController;
  75130. }(BABYLON.WebVRController));
  75131. BABYLON.GenericController = GenericController;
  75132. })(BABYLON || (BABYLON = {}));
  75133. //# sourceMappingURL=babylon.genericController.js.map
  75134. var BABYLON;
  75135. (function (BABYLON) {
  75136. /**
  75137. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  75138. */
  75139. var LoadedMeshInfo = /** @class */ (function () {
  75140. function LoadedMeshInfo() {
  75141. /**
  75142. * Map of the button meshes contained in the controller
  75143. */
  75144. this.buttonMeshes = {};
  75145. /**
  75146. * Map of the axis meshes contained in the controller
  75147. */
  75148. this.axisMeshes = {};
  75149. }
  75150. return LoadedMeshInfo;
  75151. }());
  75152. /**
  75153. * Defines the WindowsMotionController object that the state of the windows motion controller
  75154. */
  75155. var WindowsMotionController = /** @class */ (function (_super) {
  75156. __extends(WindowsMotionController, _super);
  75157. /**
  75158. * Creates a new WindowsMotionController from a gamepad
  75159. * @param vrGamepad the gamepad that the controller should be created from
  75160. */
  75161. function WindowsMotionController(vrGamepad) {
  75162. var _this = _super.call(this, vrGamepad) || this;
  75163. _this._mapping = {
  75164. // Semantic button names
  75165. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  75166. // A mapping of the button name to glTF model node name
  75167. // that should be transformed by button value.
  75168. buttonMeshNames: {
  75169. 'trigger': 'SELECT',
  75170. 'menu': 'MENU',
  75171. 'grip': 'GRASP',
  75172. 'thumbstick': 'THUMBSTICK_PRESS',
  75173. 'trackpad': 'TOUCHPAD_PRESS'
  75174. },
  75175. // This mapping is used to translate from the Motion Controller to Babylon semantics
  75176. buttonObservableNames: {
  75177. 'trigger': 'onTriggerStateChangedObservable',
  75178. 'menu': 'onSecondaryButtonStateChangedObservable',
  75179. 'grip': 'onMainButtonStateChangedObservable',
  75180. 'thumbstick': 'onPadStateChangedObservable',
  75181. 'trackpad': 'onTrackpadChangedObservable'
  75182. },
  75183. // A mapping of the axis name to glTF model node name
  75184. // that should be transformed by axis value.
  75185. // This array mirrors the browserGamepad.axes array, such that
  75186. // the mesh corresponding to axis 0 is in this array index 0.
  75187. axisMeshNames: [
  75188. 'THUMBSTICK_X',
  75189. 'THUMBSTICK_Y',
  75190. 'TOUCHPAD_TOUCH_X',
  75191. 'TOUCHPAD_TOUCH_Y'
  75192. ],
  75193. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  75194. };
  75195. /**
  75196. * Fired when the trackpad on this controller is clicked
  75197. */
  75198. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  75199. /**
  75200. * Fired when the trackpad on this controller is modified
  75201. */
  75202. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  75203. /**
  75204. * The current x and y values of this controller's trackpad
  75205. */
  75206. _this.trackpad = { x: 0, y: 0 };
  75207. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  75208. _this._loadedMeshInfo = null;
  75209. return _this;
  75210. }
  75211. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  75212. /**
  75213. * Fired when the trigger on this controller is modified
  75214. */
  75215. get: function () {
  75216. return this.onTriggerStateChangedObservable;
  75217. },
  75218. enumerable: true,
  75219. configurable: true
  75220. });
  75221. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  75222. /**
  75223. * Fired when the menu button on this controller is modified
  75224. */
  75225. get: function () {
  75226. return this.onSecondaryButtonStateChangedObservable;
  75227. },
  75228. enumerable: true,
  75229. configurable: true
  75230. });
  75231. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  75232. /**
  75233. * Fired when the grip button on this controller is modified
  75234. */
  75235. get: function () {
  75236. return this.onMainButtonStateChangedObservable;
  75237. },
  75238. enumerable: true,
  75239. configurable: true
  75240. });
  75241. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  75242. /**
  75243. * Fired when the thumbstick button on this controller is modified
  75244. */
  75245. get: function () {
  75246. return this.onPadStateChangedObservable;
  75247. },
  75248. enumerable: true,
  75249. configurable: true
  75250. });
  75251. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  75252. /**
  75253. * Fired when the touchpad button on this controller is modified
  75254. */
  75255. get: function () {
  75256. return this.onTrackpadChangedObservable;
  75257. },
  75258. enumerable: true,
  75259. configurable: true
  75260. });
  75261. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75262. /**
  75263. * Fired when the touchpad values on this controller are modified
  75264. */
  75265. get: function () {
  75266. return this.onTrackpadValuesChangedObservable;
  75267. },
  75268. enumerable: true,
  75269. configurable: true
  75270. });
  75271. WindowsMotionController.prototype._updateTrackpad = function () {
  75272. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75273. this.trackpad.x = this.browserGamepad["axes"][2];
  75274. this.trackpad.y = this.browserGamepad["axes"][3];
  75275. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75276. }
  75277. };
  75278. /**
  75279. * Called once per frame by the engine.
  75280. */
  75281. WindowsMotionController.prototype.update = function () {
  75282. _super.prototype.update.call(this);
  75283. if (this.browserGamepad.axes) {
  75284. this._updateTrackpad();
  75285. // Only need to animate axes if there is a loaded mesh
  75286. if (this._loadedMeshInfo) {
  75287. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75288. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75289. }
  75290. }
  75291. }
  75292. };
  75293. /**
  75294. * Called once for each button that changed state since the last frame
  75295. * @param buttonIdx Which button index changed
  75296. * @param state New state of the button
  75297. * @param changes Which properties on the state changed since last frame
  75298. */
  75299. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75300. var buttonName = this._mapping.buttons[buttonIdx];
  75301. if (!buttonName) {
  75302. return;
  75303. }
  75304. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75305. this._updateTrackpad();
  75306. // Only emit events for buttons that we know how to map from index to name
  75307. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75308. if (observable) {
  75309. observable.notifyObservers(state);
  75310. }
  75311. this._lerpButtonTransform(buttonName, state.value);
  75312. };
  75313. /**
  75314. * Moves the buttons on the controller mesh based on their current state
  75315. * @param buttonName the name of the button to move
  75316. * @param buttonValue the value of the button which determines the buttons new position
  75317. */
  75318. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75319. // If there is no loaded mesh, there is nothing to transform.
  75320. if (!this._loadedMeshInfo) {
  75321. return;
  75322. }
  75323. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75324. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75325. return;
  75326. }
  75327. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75328. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75329. };
  75330. /**
  75331. * Moves the axis on the controller mesh based on its current state
  75332. * @param axis the index of the axis
  75333. * @param axisValue the value of the axis which determines the meshes new position
  75334. * @hidden
  75335. */
  75336. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75337. if (!this._loadedMeshInfo) {
  75338. return;
  75339. }
  75340. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75341. if (!meshInfo) {
  75342. return;
  75343. }
  75344. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75345. return;
  75346. }
  75347. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75348. var lerpValue = axisValue * 0.5 + 0.5;
  75349. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75350. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75351. };
  75352. /**
  75353. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75354. * @param scene scene in which to add meshes
  75355. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75356. */
  75357. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75358. var _this = this;
  75359. if (forceDefault === void 0) { forceDefault = false; }
  75360. var path;
  75361. var filename;
  75362. // Checking if GLB loader is present
  75363. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75364. // Determine the device specific folder based on the ID suffix
  75365. var device = 'default';
  75366. if (this.id && !forceDefault) {
  75367. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75368. device = ((match && match[0]) || device);
  75369. }
  75370. // Hand
  75371. if (this.hand === 'left') {
  75372. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75373. }
  75374. else { // Right is the default if no hand is specified
  75375. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75376. }
  75377. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75378. }
  75379. else {
  75380. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75381. path = BABYLON.GenericController.MODEL_BASE_URL;
  75382. filename = BABYLON.GenericController.MODEL_FILENAME;
  75383. }
  75384. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75385. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75386. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75387. if (!_this._loadedMeshInfo) {
  75388. return;
  75389. }
  75390. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75391. _this.attachToMesh(_this._defaultModel);
  75392. if (meshLoaded) {
  75393. meshLoaded(_this._defaultModel);
  75394. }
  75395. }, null, function (scene, message) {
  75396. BABYLON.Tools.Log(message);
  75397. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  75398. if (!forceDefault) {
  75399. _this.initControllerMesh(scene, meshLoaded, true);
  75400. }
  75401. });
  75402. };
  75403. /**
  75404. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  75405. * can be transformed by button presses and axes values, based on this._mapping.
  75406. *
  75407. * @param scene scene in which the meshes exist
  75408. * @param meshes list of meshes that make up the controller model to process
  75409. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  75410. */
  75411. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  75412. var loadedMeshInfo = null;
  75413. // Create a new mesh to contain the glTF hierarchy
  75414. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  75415. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  75416. var childMesh = null;
  75417. for (var i = 0; i < meshes.length; i++) {
  75418. var mesh = meshes[i];
  75419. if (!mesh.parent) {
  75420. // Exclude controller meshes from picking results
  75421. mesh.isPickable = false;
  75422. // Handle root node, attach to the new parentMesh
  75423. childMesh = mesh;
  75424. break;
  75425. }
  75426. }
  75427. if (childMesh) {
  75428. childMesh.setParent(parentMesh);
  75429. // Create our mesh info. Note that this method will always return non-null.
  75430. loadedMeshInfo = this.createMeshInfo(parentMesh);
  75431. }
  75432. else {
  75433. BABYLON.Tools.Warn('Could not find root node in model file.');
  75434. }
  75435. return loadedMeshInfo;
  75436. };
  75437. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  75438. var loadedMeshInfo = new LoadedMeshInfo();
  75439. var i;
  75440. loadedMeshInfo.rootNode = rootNode;
  75441. // Reset the caches
  75442. loadedMeshInfo.buttonMeshes = {};
  75443. loadedMeshInfo.axisMeshes = {};
  75444. // Button Meshes
  75445. for (i = 0; i < this._mapping.buttons.length; i++) {
  75446. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  75447. if (!buttonMeshName) {
  75448. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  75449. continue;
  75450. }
  75451. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  75452. if (!buttonMesh) {
  75453. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  75454. continue;
  75455. }
  75456. var buttonMeshInfo = {
  75457. index: i,
  75458. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  75459. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  75460. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  75461. };
  75462. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  75463. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  75464. }
  75465. else {
  75466. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  75467. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  75468. '(VALUE: ' + !!buttonMeshInfo.value +
  75469. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  75470. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  75471. ')');
  75472. }
  75473. }
  75474. // Axis Meshes
  75475. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  75476. var axisMeshName = this._mapping.axisMeshNames[i];
  75477. if (!axisMeshName) {
  75478. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  75479. continue;
  75480. }
  75481. var axisMesh = getChildByName(rootNode, axisMeshName);
  75482. if (!axisMesh) {
  75483. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  75484. continue;
  75485. }
  75486. var axisMeshInfo = {
  75487. index: i,
  75488. value: getImmediateChildByName(axisMesh, 'VALUE'),
  75489. min: getImmediateChildByName(axisMesh, 'MIN'),
  75490. max: getImmediateChildByName(axisMesh, 'MAX')
  75491. };
  75492. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  75493. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  75494. }
  75495. else {
  75496. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  75497. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  75498. '(VALUE: ' + !!axisMeshInfo.value +
  75499. ', MIN: ' + !!axisMeshInfo.min +
  75500. ', MAX:' + !!axisMeshInfo.max +
  75501. ')');
  75502. }
  75503. }
  75504. // Pointing Ray
  75505. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  75506. if (!loadedMeshInfo.pointingPoseNode) {
  75507. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  75508. }
  75509. else {
  75510. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  75511. }
  75512. return loadedMeshInfo;
  75513. // Look through all children recursively. This will return null if no mesh exists with the given name.
  75514. function getChildByName(node, name) {
  75515. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  75516. }
  75517. // Look through only immediate children. This will return null if no mesh exists with the given name.
  75518. function getImmediateChildByName(node, name) {
  75519. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  75520. }
  75521. };
  75522. /**
  75523. * Gets the ray of the controller in the direction the controller is pointing
  75524. * @param length the length the resulting ray should be
  75525. * @returns a ray in the direction the controller is pointing
  75526. */
  75527. WindowsMotionController.prototype.getForwardRay = function (length) {
  75528. if (length === void 0) { length = 100; }
  75529. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  75530. return _super.prototype.getForwardRay.call(this, length);
  75531. }
  75532. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  75533. var origin = m.getTranslation();
  75534. var forward = new BABYLON.Vector3(0, 0, -1);
  75535. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75536. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75537. return new BABYLON.Ray(origin, direction, length);
  75538. };
  75539. /**
  75540. * Disposes of the controller
  75541. */
  75542. WindowsMotionController.prototype.dispose = function () {
  75543. _super.prototype.dispose.call(this);
  75544. this.onTrackpadChangedObservable.clear();
  75545. };
  75546. /**
  75547. * The base url used to load the left and right controller models
  75548. */
  75549. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  75550. /**
  75551. * The name of the left controller model file
  75552. */
  75553. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  75554. /**
  75555. * The name of the right controller model file
  75556. */
  75557. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  75558. /**
  75559. * The controller name prefix for this controller type
  75560. */
  75561. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  75562. /**
  75563. * The controller id pattern for this controller type
  75564. */
  75565. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  75566. return WindowsMotionController;
  75567. }(BABYLON.WebVRController));
  75568. BABYLON.WindowsMotionController = WindowsMotionController;
  75569. })(BABYLON || (BABYLON = {}));
  75570. //# sourceMappingURL=babylon.windowsMotionController.js.map
  75571. var BABYLON;
  75572. (function (BABYLON) {
  75573. /**
  75574. * Gear VR Controller
  75575. */
  75576. var GearVRController = /** @class */ (function (_super) {
  75577. __extends(GearVRController, _super);
  75578. /**
  75579. * Creates a new GearVRController from a gamepad
  75580. * @param vrGamepad the gamepad that the controller should be created from
  75581. */
  75582. function GearVRController(vrGamepad) {
  75583. var _this = _super.call(this, vrGamepad) || this;
  75584. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75585. _this._draggedRoomRotation = 0;
  75586. _this._tmpVector = new BABYLON.Vector3();
  75587. _this._buttonIndexToObservableNameMap = [
  75588. 'onTrackpadChangedObservable',
  75589. 'onTriggerStateChangedObservable' // Trigger
  75590. ];
  75591. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75592. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75593. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75594. return _this;
  75595. }
  75596. /**
  75597. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75598. * @param poseData raw pose fromthe device
  75599. */
  75600. GearVRController.prototype.updateFromDevice = function (poseData) {
  75601. _super.prototype.updateFromDevice.call(this, poseData);
  75602. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75603. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75604. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75605. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75606. // Find the radian distance away that the headset is from the controllers rotation
  75607. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75608. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75609. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75610. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75611. this._draggedRoomRotation += rotationAmount;
  75612. // Rotate controller around headset
  75613. var sin = Math.sin(-rotationAmount);
  75614. var cos = Math.cos(-rotationAmount);
  75615. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75616. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75617. }
  75618. }
  75619. }
  75620. };
  75621. /**
  75622. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75623. * @param scene scene in which to add meshes
  75624. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75625. */
  75626. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75627. var _this = this;
  75628. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75629. // Offset the controller so it will rotate around the users wrist
  75630. var mesh = new BABYLON.Mesh("", scene);
  75631. newMeshes[1].parent = mesh;
  75632. newMeshes[1].position.z = -0.15;
  75633. _this._defaultModel = mesh;
  75634. _this.attachToMesh(_this._defaultModel);
  75635. if (meshLoaded) {
  75636. meshLoaded(_this._defaultModel);
  75637. }
  75638. });
  75639. };
  75640. /**
  75641. * Called once for each button that changed state since the last frame
  75642. * @param buttonIdx Which button index changed
  75643. * @param state New state of the button
  75644. * @param changes Which properties on the state changed since last frame
  75645. */
  75646. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75647. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75648. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75649. // Only emit events for buttons that we know how to map from index to observable
  75650. var observable = this[observableName];
  75651. if (observable) {
  75652. observable.notifyObservers(state);
  75653. }
  75654. }
  75655. };
  75656. /**
  75657. * Base Url for the controller model.
  75658. */
  75659. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75660. /**
  75661. * File name for the controller model.
  75662. */
  75663. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75664. /**
  75665. * Gamepad Id prefix used to identify this controller.
  75666. */
  75667. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75668. return GearVRController;
  75669. }(BABYLON.WebVRController));
  75670. BABYLON.GearVRController = GearVRController;
  75671. })(BABYLON || (BABYLON = {}));
  75672. //# sourceMappingURL=babylon.gearVRController.js.map
  75673. var BABYLON;
  75674. (function (BABYLON) {
  75675. /**
  75676. * Google Daydream controller
  75677. */
  75678. var DaydreamController = /** @class */ (function (_super) {
  75679. __extends(DaydreamController, _super);
  75680. /**
  75681. * Creates a new DaydreamController from a gamepad
  75682. * @param vrGamepad the gamepad that the controller should be created from
  75683. */
  75684. function DaydreamController(vrGamepad) {
  75685. var _this = _super.call(this, vrGamepad) || this;
  75686. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75687. return _this;
  75688. }
  75689. /**
  75690. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75691. * @param scene scene in which to add meshes
  75692. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75693. */
  75694. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75695. var _this = this;
  75696. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75697. _this._defaultModel = newMeshes[1];
  75698. _this.attachToMesh(_this._defaultModel);
  75699. if (meshLoaded) {
  75700. meshLoaded(_this._defaultModel);
  75701. }
  75702. });
  75703. };
  75704. /**
  75705. * Called once for each button that changed state since the last frame
  75706. * @param buttonIdx Which button index changed
  75707. * @param state New state of the button
  75708. * @param changes Which properties on the state changed since last frame
  75709. */
  75710. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75711. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75712. if (buttonIdx === 0) {
  75713. var observable = this.onTriggerStateChangedObservable;
  75714. if (observable) {
  75715. observable.notifyObservers(state);
  75716. }
  75717. }
  75718. else {
  75719. // If the app or home buttons are ever made available
  75720. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75721. }
  75722. };
  75723. /**
  75724. * Base Url for the controller model.
  75725. */
  75726. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75727. /**
  75728. * File name for the controller model.
  75729. */
  75730. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75731. /**
  75732. * Gamepad Id prefix used to identify Daydream Controller.
  75733. */
  75734. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75735. return DaydreamController;
  75736. }(BABYLON.WebVRController));
  75737. BABYLON.DaydreamController = DaydreamController;
  75738. })(BABYLON || (BABYLON = {}));
  75739. //# sourceMappingURL=babylon.daydreamController.js.map
  75740. var BABYLON;
  75741. (function (BABYLON) {
  75742. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75743. get: function () {
  75744. if (!this._gamepadManager) {
  75745. this._gamepadManager = new BABYLON.GamepadManager(this);
  75746. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75747. if (!component) {
  75748. component = new GamepadSystemSceneComponent(this);
  75749. this._addComponent(component);
  75750. }
  75751. }
  75752. return this._gamepadManager;
  75753. },
  75754. enumerable: true,
  75755. configurable: true
  75756. });
  75757. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75758. this.add(new BABYLON.FreeCameraGamepadInput());
  75759. return this;
  75760. };
  75761. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75762. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75763. return this;
  75764. };
  75765. /**
  75766. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75767. */
  75768. var GamepadSystemSceneComponent = /** @class */ (function () {
  75769. /**
  75770. * Creates a new instance of the component for the given scene
  75771. * @param scene Defines the scene to register the component in
  75772. */
  75773. function GamepadSystemSceneComponent(scene) {
  75774. /**
  75775. * The component name helpfull to identify the component in the list of scene components.
  75776. */
  75777. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75778. this.scene = scene;
  75779. }
  75780. /**
  75781. * Registers the component in a given scene
  75782. */
  75783. GamepadSystemSceneComponent.prototype.register = function () {
  75784. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75785. };
  75786. /**
  75787. * Rebuilds the elements related to this component in case of
  75788. * context lost for instance.
  75789. */
  75790. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75791. // Nothing to do for gamepads
  75792. };
  75793. /**
  75794. * Disposes the component and the associated ressources
  75795. */
  75796. GamepadSystemSceneComponent.prototype.dispose = function () {
  75797. var gamepadManager = this.scene._gamepadManager;
  75798. if (gamepadManager) {
  75799. gamepadManager.dispose();
  75800. this.scene._gamepadManager = null;
  75801. }
  75802. };
  75803. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75804. var gamepadManager = this.scene._gamepadManager;
  75805. if (gamepadManager && gamepadManager._isMonitoring) {
  75806. gamepadManager._checkGamepadsStatus();
  75807. }
  75808. };
  75809. return GamepadSystemSceneComponent;
  75810. }());
  75811. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75812. })(BABYLON || (BABYLON = {}));
  75813. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75814. var BABYLON;
  75815. (function (BABYLON) {
  75816. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75817. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75818. });
  75819. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75820. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75821. });
  75822. var FollowCamera = /** @class */ (function (_super) {
  75823. __extends(FollowCamera, _super);
  75824. function FollowCamera(name, position, scene, lockedTarget) {
  75825. if (lockedTarget === void 0) { lockedTarget = null; }
  75826. var _this = _super.call(this, name, position, scene) || this;
  75827. _this.radius = 12;
  75828. _this.rotationOffset = 0;
  75829. _this.heightOffset = 4;
  75830. _this.cameraAcceleration = 0.05;
  75831. _this.maxCameraSpeed = 20;
  75832. _this.lockedTarget = lockedTarget;
  75833. return _this;
  75834. }
  75835. FollowCamera.prototype.getRadians = function (degrees) {
  75836. return degrees * Math.PI / 180;
  75837. };
  75838. FollowCamera.prototype.follow = function (cameraTarget) {
  75839. if (!cameraTarget)
  75840. return;
  75841. var yRotation;
  75842. if (cameraTarget.rotationQuaternion) {
  75843. var rotMatrix = new BABYLON.Matrix();
  75844. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75845. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75846. }
  75847. else {
  75848. yRotation = cameraTarget.rotation.y;
  75849. }
  75850. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75851. var targetPosition = cameraTarget.getAbsolutePosition();
  75852. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  75853. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  75854. var dx = targetX - this.position.x;
  75855. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  75856. var dz = (targetZ) - this.position.z;
  75857. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  75858. var vy = dy * this.cameraAcceleration;
  75859. var vz = dz * this.cameraAcceleration * 2;
  75860. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  75861. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75862. }
  75863. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  75864. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75865. }
  75866. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  75867. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75868. }
  75869. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  75870. this.setTarget(targetPosition);
  75871. };
  75872. /** @hidden */
  75873. FollowCamera.prototype._checkInputs = function () {
  75874. _super.prototype._checkInputs.call(this);
  75875. if (this.lockedTarget) {
  75876. this.follow(this.lockedTarget);
  75877. }
  75878. };
  75879. FollowCamera.prototype.getClassName = function () {
  75880. return "FollowCamera";
  75881. };
  75882. __decorate([
  75883. BABYLON.serialize()
  75884. ], FollowCamera.prototype, "radius", void 0);
  75885. __decorate([
  75886. BABYLON.serialize()
  75887. ], FollowCamera.prototype, "rotationOffset", void 0);
  75888. __decorate([
  75889. BABYLON.serialize()
  75890. ], FollowCamera.prototype, "heightOffset", void 0);
  75891. __decorate([
  75892. BABYLON.serialize()
  75893. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  75894. __decorate([
  75895. BABYLON.serialize()
  75896. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  75897. __decorate([
  75898. BABYLON.serializeAsMeshReference("lockedTargetId")
  75899. ], FollowCamera.prototype, "lockedTarget", void 0);
  75900. return FollowCamera;
  75901. }(BABYLON.TargetCamera));
  75902. BABYLON.FollowCamera = FollowCamera;
  75903. var ArcFollowCamera = /** @class */ (function (_super) {
  75904. __extends(ArcFollowCamera, _super);
  75905. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  75906. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  75907. _this.alpha = alpha;
  75908. _this.beta = beta;
  75909. _this.radius = radius;
  75910. _this.target = target;
  75911. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  75912. _this.follow();
  75913. return _this;
  75914. }
  75915. ArcFollowCamera.prototype.follow = function () {
  75916. if (!this.target) {
  75917. return;
  75918. }
  75919. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  75920. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  75921. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  75922. var targetPosition = this.target.getAbsolutePosition();
  75923. this.position = targetPosition.add(this._cartesianCoordinates);
  75924. this.setTarget(targetPosition);
  75925. };
  75926. /** @hidden */
  75927. ArcFollowCamera.prototype._checkInputs = function () {
  75928. _super.prototype._checkInputs.call(this);
  75929. this.follow();
  75930. };
  75931. ArcFollowCamera.prototype.getClassName = function () {
  75932. return "ArcFollowCamera";
  75933. };
  75934. return ArcFollowCamera;
  75935. }(BABYLON.TargetCamera));
  75936. BABYLON.ArcFollowCamera = ArcFollowCamera;
  75937. })(BABYLON || (BABYLON = {}));
  75938. //# sourceMappingURL=babylon.followCamera.js.map
  75939. var BABYLON;
  75940. (function (BABYLON) {
  75941. // We're mainly based on the logic defined into the FreeCamera code
  75942. var UniversalCamera = /** @class */ (function (_super) {
  75943. __extends(UniversalCamera, _super);
  75944. //-- end properties for backward compatibility for inputs
  75945. function UniversalCamera(name, position, scene) {
  75946. var _this = _super.call(this, name, position, scene) || this;
  75947. _this.inputs.addGamepad();
  75948. return _this;
  75949. }
  75950. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  75951. //-- Begin properties for backward compatibility for inputs
  75952. get: function () {
  75953. var gamepad = this.inputs.attached["gamepad"];
  75954. if (gamepad)
  75955. return gamepad.gamepadAngularSensibility;
  75956. return 0;
  75957. },
  75958. set: function (value) {
  75959. var gamepad = this.inputs.attached["gamepad"];
  75960. if (gamepad)
  75961. gamepad.gamepadAngularSensibility = value;
  75962. },
  75963. enumerable: true,
  75964. configurable: true
  75965. });
  75966. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75967. get: function () {
  75968. var gamepad = this.inputs.attached["gamepad"];
  75969. if (gamepad)
  75970. return gamepad.gamepadMoveSensibility;
  75971. return 0;
  75972. },
  75973. set: function (value) {
  75974. var gamepad = this.inputs.attached["gamepad"];
  75975. if (gamepad)
  75976. gamepad.gamepadMoveSensibility = value;
  75977. },
  75978. enumerable: true,
  75979. configurable: true
  75980. });
  75981. UniversalCamera.prototype.getClassName = function () {
  75982. return "UniversalCamera";
  75983. };
  75984. return UniversalCamera;
  75985. }(BABYLON.TouchCamera));
  75986. BABYLON.UniversalCamera = UniversalCamera;
  75987. })(BABYLON || (BABYLON = {}));
  75988. //# sourceMappingURL=babylon.universalCamera.js.map
  75989. var BABYLON;
  75990. (function (BABYLON) {
  75991. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75992. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75993. });
  75994. // We're mainly based on the logic defined into the FreeCamera code
  75995. var GamepadCamera = /** @class */ (function (_super) {
  75996. __extends(GamepadCamera, _super);
  75997. //-- end properties for backward compatibility for inputs
  75998. function GamepadCamera(name, position, scene) {
  75999. return _super.call(this, name, position, scene) || this;
  76000. }
  76001. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  76002. //-- Begin properties for backward compatibility for inputs
  76003. get: function () {
  76004. var gamepad = this.inputs.attached["gamepad"];
  76005. if (gamepad)
  76006. return gamepad.gamepadAngularSensibility;
  76007. return 0;
  76008. },
  76009. set: function (value) {
  76010. var gamepad = this.inputs.attached["gamepad"];
  76011. if (gamepad)
  76012. gamepad.gamepadAngularSensibility = value;
  76013. },
  76014. enumerable: true,
  76015. configurable: true
  76016. });
  76017. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  76018. get: function () {
  76019. var gamepad = this.inputs.attached["gamepad"];
  76020. if (gamepad)
  76021. return gamepad.gamepadMoveSensibility;
  76022. return 0;
  76023. },
  76024. set: function (value) {
  76025. var gamepad = this.inputs.attached["gamepad"];
  76026. if (gamepad)
  76027. gamepad.gamepadMoveSensibility = value;
  76028. },
  76029. enumerable: true,
  76030. configurable: true
  76031. });
  76032. GamepadCamera.prototype.getClassName = function () {
  76033. return "GamepadCamera";
  76034. };
  76035. return GamepadCamera;
  76036. }(BABYLON.UniversalCamera));
  76037. BABYLON.GamepadCamera = GamepadCamera;
  76038. })(BABYLON || (BABYLON = {}));
  76039. //# sourceMappingURL=babylon.gamepadCamera.js.map
  76040. var BABYLON;
  76041. (function (BABYLON) {
  76042. var PostProcessRenderPipelineManager = /** @class */ (function () {
  76043. function PostProcessRenderPipelineManager() {
  76044. this._renderPipelines = {};
  76045. }
  76046. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  76047. this._renderPipelines[renderPipeline._name] = renderPipeline;
  76048. };
  76049. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  76050. if (unique === void 0) { unique = false; }
  76051. var renderPipeline = this._renderPipelines[renderPipelineName];
  76052. if (!renderPipeline) {
  76053. return;
  76054. }
  76055. renderPipeline._attachCameras(cameras, unique);
  76056. };
  76057. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  76058. var renderPipeline = this._renderPipelines[renderPipelineName];
  76059. if (!renderPipeline) {
  76060. return;
  76061. }
  76062. renderPipeline._detachCameras(cameras);
  76063. };
  76064. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76065. var renderPipeline = this._renderPipelines[renderPipelineName];
  76066. if (!renderPipeline) {
  76067. return;
  76068. }
  76069. renderPipeline._enableEffect(renderEffectName, cameras);
  76070. };
  76071. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  76072. var renderPipeline = this._renderPipelines[renderPipelineName];
  76073. if (!renderPipeline) {
  76074. return;
  76075. }
  76076. renderPipeline._disableEffect(renderEffectName, cameras);
  76077. };
  76078. PostProcessRenderPipelineManager.prototype.update = function () {
  76079. for (var renderPipelineName in this._renderPipelines) {
  76080. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76081. var pipeline = this._renderPipelines[renderPipelineName];
  76082. if (!pipeline.isSupported) {
  76083. pipeline.dispose();
  76084. delete this._renderPipelines[renderPipelineName];
  76085. }
  76086. else {
  76087. pipeline._update();
  76088. }
  76089. }
  76090. }
  76091. };
  76092. /** @hidden */
  76093. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  76094. for (var renderPipelineName in this._renderPipelines) {
  76095. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76096. var pipeline = this._renderPipelines[renderPipelineName];
  76097. pipeline._rebuild();
  76098. }
  76099. }
  76100. };
  76101. PostProcessRenderPipelineManager.prototype.dispose = function () {
  76102. for (var renderPipelineName in this._renderPipelines) {
  76103. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  76104. var pipeline = this._renderPipelines[renderPipelineName];
  76105. pipeline.dispose();
  76106. }
  76107. }
  76108. };
  76109. return PostProcessRenderPipelineManager;
  76110. }());
  76111. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  76112. })(BABYLON || (BABYLON = {}));
  76113. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  76114. var BABYLON;
  76115. (function (BABYLON) {
  76116. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  76117. get: function () {
  76118. if (!this._postProcessRenderPipelineManager) {
  76119. // Register the G Buffer component to the scene.
  76120. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  76121. if (!component) {
  76122. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  76123. this._addComponent(component);
  76124. }
  76125. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  76126. }
  76127. return this._postProcessRenderPipelineManager;
  76128. },
  76129. enumerable: true,
  76130. configurable: true
  76131. });
  76132. /**
  76133. * Defines the Render Pipeline scene component responsible to rendering pipelines
  76134. */
  76135. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  76136. /**
  76137. * Creates a new instance of the component for the given scene
  76138. * @param scene Defines the scene to register the component in
  76139. */
  76140. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  76141. /**
  76142. * The component name helpfull to identify the component in the list of scene components.
  76143. */
  76144. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  76145. this.scene = scene;
  76146. }
  76147. /**
  76148. * Registers the component in a given scene
  76149. */
  76150. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  76151. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  76152. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_REBUILDGEOMETRY_POSTPROCESSRENDERPIPELINEMANAGER, this, this._rebuildGeometry);
  76153. };
  76154. /**
  76155. * Rebuilds the elements related to this component in case of
  76156. * context lost for instance.
  76157. */
  76158. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  76159. // Nothing to do for this component
  76160. };
  76161. /**
  76162. * Disposes the component and the associated ressources
  76163. */
  76164. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  76165. if (this.scene._postProcessRenderPipelineManager) {
  76166. this.scene._postProcessRenderPipelineManager.dispose();
  76167. }
  76168. };
  76169. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76170. if (this.scene._postProcessRenderPipelineManager) {
  76171. this.scene._postProcessRenderPipelineManager.update();
  76172. }
  76173. };
  76174. PostProcessRenderPipelineManagerSceneComponent.prototype._rebuildGeometry = function () {
  76175. if (this.scene._postProcessRenderPipelineManager) {
  76176. this.scene._postProcessRenderPipelineManager._rebuild();
  76177. }
  76178. };
  76179. return PostProcessRenderPipelineManagerSceneComponent;
  76180. }());
  76181. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  76182. })(BABYLON || (BABYLON = {}));
  76183. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  76184. var BABYLON;
  76185. (function (BABYLON) {
  76186. /**
  76187. * This represents a set of one or more post processes in Babylon.
  76188. * A post process can be used to apply a shader to a texture after it is rendered.
  76189. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  76190. */
  76191. var PostProcessRenderEffect = /** @class */ (function () {
  76192. /**
  76193. * Instantiates a post process render effect.
  76194. * A post process can be used to apply a shader to a texture after it is rendered.
  76195. * @param engine The engine the effect is tied to
  76196. * @param name The name of the effect
  76197. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  76198. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  76199. */
  76200. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  76201. this._name = name;
  76202. this._singleInstance = singleInstance || true;
  76203. this._getPostProcesses = getPostProcesses;
  76204. this._cameras = {};
  76205. this._indicesForCamera = {};
  76206. this._postProcesses = {};
  76207. }
  76208. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  76209. /**
  76210. * Checks if all the post processes in the effect are supported.
  76211. */
  76212. get: function () {
  76213. for (var index in this._postProcesses) {
  76214. if (this._postProcesses.hasOwnProperty(index)) {
  76215. var pps = this._postProcesses[index];
  76216. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  76217. if (!pps[ppIndex].isSupported) {
  76218. return false;
  76219. }
  76220. }
  76221. }
  76222. }
  76223. return true;
  76224. },
  76225. enumerable: true,
  76226. configurable: true
  76227. });
  76228. /**
  76229. * Updates the current state of the effect
  76230. * @hidden
  76231. */
  76232. PostProcessRenderEffect.prototype._update = function () {
  76233. };
  76234. /**
  76235. * Attaches the effect on cameras
  76236. * @param cameras The camera to attach to.
  76237. * @hidden
  76238. */
  76239. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  76240. var _this = this;
  76241. var cameraKey;
  76242. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76243. if (!cams) {
  76244. return;
  76245. }
  76246. for (var i = 0; i < cams.length; i++) {
  76247. var camera = cams[i];
  76248. var cameraName = camera.name;
  76249. if (this._singleInstance) {
  76250. cameraKey = 0;
  76251. }
  76252. else {
  76253. cameraKey = cameraName;
  76254. }
  76255. if (!this._postProcesses[cameraKey]) {
  76256. var postProcess = this._getPostProcesses();
  76257. if (postProcess) {
  76258. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  76259. }
  76260. }
  76261. if (!this._indicesForCamera[cameraName]) {
  76262. this._indicesForCamera[cameraName] = [];
  76263. }
  76264. this._postProcesses[cameraKey].forEach(function (postProcess) {
  76265. var index = camera.attachPostProcess(postProcess);
  76266. _this._indicesForCamera[cameraName].push(index);
  76267. });
  76268. if (!this._cameras[cameraName]) {
  76269. this._cameras[cameraName] = camera;
  76270. }
  76271. }
  76272. };
  76273. /**
  76274. * Detatches the effect on cameras
  76275. * @param cameras The camera to detatch from.
  76276. * @hidden
  76277. */
  76278. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  76279. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76280. if (!cams) {
  76281. return;
  76282. }
  76283. for (var i = 0; i < cams.length; i++) {
  76284. var camera = cams[i];
  76285. var cameraName = camera.name;
  76286. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76287. camera.detachPostProcess(postProcess);
  76288. });
  76289. if (this._cameras[cameraName]) {
  76290. //this._indicesForCamera.splice(index, 1);
  76291. this._cameras[cameraName] = null;
  76292. }
  76293. }
  76294. };
  76295. /**
  76296. * Enables the effect on given cameras
  76297. * @param cameras The camera to enable.
  76298. * @hidden
  76299. */
  76300. PostProcessRenderEffect.prototype._enable = function (cameras) {
  76301. var _this = this;
  76302. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76303. if (!cams) {
  76304. return;
  76305. }
  76306. for (var i = 0; i < cams.length; i++) {
  76307. var camera = cams[i];
  76308. var cameraName = camera.name;
  76309. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  76310. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  76311. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76312. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  76313. });
  76314. }
  76315. }
  76316. }
  76317. };
  76318. /**
  76319. * Disables the effect on the given cameras
  76320. * @param cameras The camera to disable.
  76321. * @hidden
  76322. */
  76323. PostProcessRenderEffect.prototype._disable = function (cameras) {
  76324. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76325. if (!cams) {
  76326. return;
  76327. }
  76328. for (var i = 0; i < cams.length; i++) {
  76329. var camera = cams[i];
  76330. var cameraName = camera.name;
  76331. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76332. camera.detachPostProcess(postProcess);
  76333. });
  76334. }
  76335. };
  76336. /**
  76337. * Gets a list of the post processes contained in the effect.
  76338. * @param camera The camera to get the post processes on.
  76339. * @returns The list of the post processes in the effect.
  76340. */
  76341. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76342. if (this._singleInstance) {
  76343. return this._postProcesses[0];
  76344. }
  76345. else {
  76346. if (!camera) {
  76347. return null;
  76348. }
  76349. return this._postProcesses[camera.name];
  76350. }
  76351. };
  76352. return PostProcessRenderEffect;
  76353. }());
  76354. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76355. })(BABYLON || (BABYLON = {}));
  76356. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76357. var BABYLON;
  76358. (function (BABYLON) {
  76359. var PostProcessRenderPipeline = /** @class */ (function () {
  76360. function PostProcessRenderPipeline(engine, name) {
  76361. this.engine = engine;
  76362. this._name = name;
  76363. this._renderEffects = {};
  76364. this._renderEffectsForIsolatedPass = new Array();
  76365. this._cameras = [];
  76366. }
  76367. PostProcessRenderPipeline.prototype.getClassName = function () {
  76368. return "PostProcessRenderPipeline";
  76369. };
  76370. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76371. get: function () {
  76372. for (var renderEffectName in this._renderEffects) {
  76373. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76374. if (!this._renderEffects[renderEffectName].isSupported) {
  76375. return false;
  76376. }
  76377. }
  76378. }
  76379. return true;
  76380. },
  76381. enumerable: true,
  76382. configurable: true
  76383. });
  76384. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76385. this._renderEffects[renderEffect._name] = renderEffect;
  76386. };
  76387. // private
  76388. /** @hidden */
  76389. PostProcessRenderPipeline.prototype._rebuild = function () {
  76390. };
  76391. /** @hidden */
  76392. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  76393. var renderEffects = this._renderEffects[renderEffectName];
  76394. if (!renderEffects) {
  76395. return;
  76396. }
  76397. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76398. };
  76399. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  76400. var renderEffects = this._renderEffects[renderEffectName];
  76401. if (!renderEffects) {
  76402. return;
  76403. }
  76404. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76405. };
  76406. /** @hidden */
  76407. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  76408. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76409. if (!cams) {
  76410. return;
  76411. }
  76412. var indicesToDelete = [];
  76413. var i;
  76414. for (i = 0; i < cams.length; i++) {
  76415. var camera = cams[i];
  76416. var cameraName = camera.name;
  76417. if (this._cameras.indexOf(camera) === -1) {
  76418. this._cameras[cameraName] = camera;
  76419. }
  76420. else if (unique) {
  76421. indicesToDelete.push(i);
  76422. }
  76423. }
  76424. for (i = 0; i < indicesToDelete.length; i++) {
  76425. cameras.splice(indicesToDelete[i], 1);
  76426. }
  76427. for (var renderEffectName in this._renderEffects) {
  76428. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76429. this._renderEffects[renderEffectName]._attachCameras(cams);
  76430. }
  76431. }
  76432. };
  76433. /** @hidden */
  76434. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  76435. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76436. if (!cams) {
  76437. return;
  76438. }
  76439. for (var renderEffectName in this._renderEffects) {
  76440. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76441. this._renderEffects[renderEffectName]._detachCameras(cams);
  76442. }
  76443. }
  76444. for (var i = 0; i < cams.length; i++) {
  76445. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  76446. }
  76447. };
  76448. /** @hidden */
  76449. PostProcessRenderPipeline.prototype._update = function () {
  76450. for (var renderEffectName in this._renderEffects) {
  76451. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76452. this._renderEffects[renderEffectName]._update();
  76453. }
  76454. }
  76455. for (var i = 0; i < this._cameras.length; i++) {
  76456. var cameraName = this._cameras[i].name;
  76457. if (this._renderEffectsForIsolatedPass[cameraName]) {
  76458. this._renderEffectsForIsolatedPass[cameraName]._update();
  76459. }
  76460. }
  76461. };
  76462. /** @hidden */
  76463. PostProcessRenderPipeline.prototype._reset = function () {
  76464. this._renderEffects = {};
  76465. this._renderEffectsForIsolatedPass = new Array();
  76466. };
  76467. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  76468. // 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)
  76469. var effectKeys = Object.keys(this._renderEffects);
  76470. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  76471. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  76472. if (postProcesses) {
  76473. postProcesses[0].samples = sampleCount;
  76474. return true;
  76475. }
  76476. }
  76477. return false;
  76478. };
  76479. PostProcessRenderPipeline.prototype.dispose = function () {
  76480. // Must be implemented by children
  76481. };
  76482. __decorate([
  76483. BABYLON.serialize()
  76484. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  76485. return PostProcessRenderPipeline;
  76486. }());
  76487. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  76488. })(BABYLON || (BABYLON = {}));
  76489. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  76490. var BABYLON;
  76491. (function (BABYLON) {
  76492. /**
  76493. * This represents a depth renderer in Babylon.
  76494. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  76495. */
  76496. var DepthRenderer = /** @class */ (function () {
  76497. /**
  76498. * Instantiates a depth renderer
  76499. * @param scene The scene the renderer belongs to
  76500. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  76501. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  76502. */
  76503. function DepthRenderer(scene, type, camera) {
  76504. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  76505. if (camera === void 0) { camera = null; }
  76506. var _this = this;
  76507. this._scene = scene;
  76508. // Register the G Buffer component to the scene.
  76509. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  76510. if (!component) {
  76511. component = new BABYLON.DepthRendererSceneComponent(scene);
  76512. scene._addComponent(component);
  76513. }
  76514. this._camera = camera;
  76515. var engine = scene.getEngine();
  76516. // Render target
  76517. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  76518. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76519. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76520. this._depthMap.refreshRate = 1;
  76521. this._depthMap.renderParticles = false;
  76522. this._depthMap.renderList = null;
  76523. // Camera to get depth map from to support multiple concurrent cameras
  76524. this._depthMap.activeCamera = this._camera;
  76525. this._depthMap.ignoreCameraViewport = true;
  76526. this._depthMap.useCameraPostProcesses = false;
  76527. // set default depth value to 1.0 (far away)
  76528. this._depthMap.onClearObservable.add(function (engine) {
  76529. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  76530. });
  76531. // Custom render function
  76532. var renderSubMesh = function (subMesh) {
  76533. var mesh = subMesh.getRenderingMesh();
  76534. var scene = _this._scene;
  76535. var engine = scene.getEngine();
  76536. var material = subMesh.getMaterial();
  76537. if (!material) {
  76538. return;
  76539. }
  76540. // Culling and reverse (right handed system)
  76541. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76542. // Managing instances
  76543. var batch = mesh._getInstancesRenderList(subMesh._id);
  76544. if (batch.mustReturn) {
  76545. return;
  76546. }
  76547. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76548. var camera = _this._camera || scene.activeCamera;
  76549. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  76550. engine.enableEffect(_this._effect);
  76551. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76552. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76553. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  76554. // Alpha test
  76555. if (material && material.needAlphaTesting()) {
  76556. var alphaTexture = material.getAlphaTestTexture();
  76557. if (alphaTexture) {
  76558. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76559. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76560. }
  76561. }
  76562. // Bones
  76563. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76564. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76565. }
  76566. // Draw
  76567. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76568. }
  76569. };
  76570. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76571. var index;
  76572. if (depthOnlySubMeshes.length) {
  76573. engine.setColorWrite(false);
  76574. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76575. renderSubMesh(depthOnlySubMeshes.data[index]);
  76576. }
  76577. engine.setColorWrite(true);
  76578. }
  76579. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76580. renderSubMesh(opaqueSubMeshes.data[index]);
  76581. }
  76582. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76583. renderSubMesh(alphaTestSubMeshes.data[index]);
  76584. }
  76585. };
  76586. }
  76587. /**
  76588. * Creates the depth rendering effect and checks if the effect is ready.
  76589. * @param subMesh The submesh to be used to render the depth map of
  76590. * @param useInstances If multiple world instances should be used
  76591. * @returns if the depth renderer is ready to render the depth map
  76592. */
  76593. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  76594. var material = subMesh.getMaterial();
  76595. if (material.disableDepthWrite) {
  76596. return false;
  76597. }
  76598. var defines = [];
  76599. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76600. var mesh = subMesh.getMesh();
  76601. // Alpha test
  76602. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  76603. defines.push("#define ALPHATEST");
  76604. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76605. attribs.push(BABYLON.VertexBuffer.UVKind);
  76606. defines.push("#define UV1");
  76607. }
  76608. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76609. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76610. defines.push("#define UV2");
  76611. }
  76612. }
  76613. // Bones
  76614. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76617. if (mesh.numBoneInfluencers > 4) {
  76618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76620. }
  76621. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76622. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76623. }
  76624. else {
  76625. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76626. }
  76627. // Instances
  76628. if (useInstances) {
  76629. defines.push("#define INSTANCES");
  76630. attribs.push("world0");
  76631. attribs.push("world1");
  76632. attribs.push("world2");
  76633. attribs.push("world3");
  76634. }
  76635. // Get correct effect
  76636. var join = defines.join("\n");
  76637. if (this._cachedDefines !== join) {
  76638. this._cachedDefines = join;
  76639. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  76640. }
  76641. return this._effect.isReady();
  76642. };
  76643. /**
  76644. * Gets the texture which the depth map will be written to.
  76645. * @returns The depth map texture
  76646. */
  76647. DepthRenderer.prototype.getDepthMap = function () {
  76648. return this._depthMap;
  76649. };
  76650. /**
  76651. * Disposes of the depth renderer.
  76652. */
  76653. DepthRenderer.prototype.dispose = function () {
  76654. this._depthMap.dispose();
  76655. };
  76656. return DepthRenderer;
  76657. }());
  76658. BABYLON.DepthRenderer = DepthRenderer;
  76659. })(BABYLON || (BABYLON = {}));
  76660. //# sourceMappingURL=babylon.depthRenderer.js.map
  76661. var BABYLON;
  76662. (function (BABYLON) {
  76663. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  76664. camera = camera || this.activeCamera;
  76665. if (!camera) {
  76666. throw "No camera available to enable depth renderer";
  76667. }
  76668. if (!this._depthRenderer) {
  76669. this._depthRenderer = {};
  76670. }
  76671. if (!this._depthRenderer[camera.id]) {
  76672. var textureType = 0;
  76673. if (this.getEngine().getCaps().textureHalfFloatRender) {
  76674. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76675. }
  76676. else if (this.getEngine().getCaps().textureFloatRender) {
  76677. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76678. }
  76679. else {
  76680. throw "Depth renderer does not support int texture type";
  76681. }
  76682. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  76683. }
  76684. return this._depthRenderer[camera.id];
  76685. };
  76686. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  76687. camera = camera || this.activeCamera;
  76688. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  76689. return;
  76690. }
  76691. this._depthRenderer[camera.id].dispose();
  76692. delete this._depthRenderer[camera.id];
  76693. };
  76694. /**
  76695. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  76696. * in several rendering techniques.
  76697. */
  76698. var DepthRendererSceneComponent = /** @class */ (function () {
  76699. /**
  76700. * Creates a new instance of the component for the given scene
  76701. * @param scene Defines the scene to register the component in
  76702. */
  76703. function DepthRendererSceneComponent(scene) {
  76704. /**
  76705. * The component name helpfull to identify the component in the list of scene components.
  76706. */
  76707. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  76708. this.scene = scene;
  76709. }
  76710. /**
  76711. * Registers the component in a given scene
  76712. */
  76713. DepthRendererSceneComponent.prototype.register = function () {
  76714. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  76715. };
  76716. /**
  76717. * Rebuilds the elements related to this component in case of
  76718. * context lost for instance.
  76719. */
  76720. DepthRendererSceneComponent.prototype.rebuild = function () {
  76721. // Nothing to do for this component
  76722. };
  76723. /**
  76724. * Disposes the component and the associated ressources
  76725. */
  76726. DepthRendererSceneComponent.prototype.dispose = function () {
  76727. for (var key in this.scene._depthRenderer) {
  76728. this.scene._depthRenderer[key].dispose();
  76729. }
  76730. };
  76731. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  76732. if (this.scene._depthRenderer) {
  76733. for (var key in this.scene._depthRenderer) {
  76734. renderTargets.push(this.scene._depthRenderer[key].getDepthMap());
  76735. }
  76736. }
  76737. };
  76738. return DepthRendererSceneComponent;
  76739. }());
  76740. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  76741. })(BABYLON || (BABYLON = {}));
  76742. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  76743. var BABYLON;
  76744. (function (BABYLON) {
  76745. /**
  76746. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76747. */
  76748. var GeometryBufferRenderer = /** @class */ (function () {
  76749. /**
  76750. * Creates a new G Buffer for the scene
  76751. * @param scene The scene the buffer belongs to
  76752. * @param ratio How big is the buffer related to the main canvas.
  76753. */
  76754. function GeometryBufferRenderer(scene, ratio) {
  76755. if (ratio === void 0) { ratio = 1; }
  76756. this._enablePosition = false;
  76757. this._scene = scene;
  76758. this._ratio = ratio;
  76759. // Register the G Buffer component to the scene.
  76760. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  76761. if (!component) {
  76762. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  76763. scene._addComponent(component);
  76764. }
  76765. // Render target
  76766. this._createRenderTargets();
  76767. }
  76768. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76769. /**
  76770. * Set the render list (meshes to be rendered) used in the G buffer.
  76771. */
  76772. set: function (meshes) {
  76773. this._multiRenderTarget.renderList = meshes;
  76774. },
  76775. enumerable: true,
  76776. configurable: true
  76777. });
  76778. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76779. /**
  76780. * Gets wether or not G buffer are supported by the running hardware.
  76781. * This requires draw buffer supports
  76782. */
  76783. get: function () {
  76784. return this._multiRenderTarget.isSupported;
  76785. },
  76786. enumerable: true,
  76787. configurable: true
  76788. });
  76789. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76790. /**
  76791. * Gets wether or not position are enabled for the G buffer.
  76792. */
  76793. get: function () {
  76794. return this._enablePosition;
  76795. },
  76796. /**
  76797. * Sets wether or not position are enabled for the G buffer.
  76798. */
  76799. set: function (enable) {
  76800. this._enablePosition = enable;
  76801. this.dispose();
  76802. this._createRenderTargets();
  76803. },
  76804. enumerable: true,
  76805. configurable: true
  76806. });
  76807. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76808. /**
  76809. * Gets the scene associated with the buffer.
  76810. */
  76811. get: function () {
  76812. return this._scene;
  76813. },
  76814. enumerable: true,
  76815. configurable: true
  76816. });
  76817. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76818. /**
  76819. * Gets the ratio used by the buffer during its creation.
  76820. * How big is the buffer related to the main canvas.
  76821. */
  76822. get: function () {
  76823. return this._ratio;
  76824. },
  76825. enumerable: true,
  76826. configurable: true
  76827. });
  76828. /**
  76829. * Checks wether everything is ready to render a submesh to the G buffer.
  76830. * @param subMesh the submesh to check readiness for
  76831. * @param useInstances is the mesh drawn using instance or not
  76832. * @returns true if ready otherwise false
  76833. */
  76834. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76835. var material = subMesh.getMaterial();
  76836. if (material && material.disableDepthWrite) {
  76837. return false;
  76838. }
  76839. var defines = [];
  76840. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76841. var mesh = subMesh.getMesh();
  76842. // Alpha test
  76843. if (material && material.needAlphaTesting()) {
  76844. defines.push("#define ALPHATEST");
  76845. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76846. attribs.push(BABYLON.VertexBuffer.UVKind);
  76847. defines.push("#define UV1");
  76848. }
  76849. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76850. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76851. defines.push("#define UV2");
  76852. }
  76853. }
  76854. // Buffers
  76855. if (this._enablePosition) {
  76856. defines.push("#define POSITION");
  76857. }
  76858. // Bones
  76859. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76860. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76861. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76862. if (mesh.numBoneInfluencers > 4) {
  76863. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76864. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76865. }
  76866. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76867. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76868. }
  76869. else {
  76870. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76871. }
  76872. // Instances
  76873. if (useInstances) {
  76874. defines.push("#define INSTANCES");
  76875. attribs.push("world0");
  76876. attribs.push("world1");
  76877. attribs.push("world2");
  76878. attribs.push("world3");
  76879. }
  76880. // Get correct effect
  76881. var join = defines.join("\n");
  76882. if (this._cachedDefines !== join) {
  76883. this._cachedDefines = join;
  76884. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76885. }
  76886. return this._effect.isReady();
  76887. };
  76888. /**
  76889. * Gets the current underlying G Buffer.
  76890. * @returns the buffer
  76891. */
  76892. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76893. return this._multiRenderTarget;
  76894. };
  76895. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76896. /**
  76897. * Gets the number of samples used to render the buffer (anti aliasing).
  76898. */
  76899. get: function () {
  76900. return this._multiRenderTarget.samples;
  76901. },
  76902. /**
  76903. * Sets the number of samples used to render the buffer (anti aliasing).
  76904. */
  76905. set: function (value) {
  76906. this._multiRenderTarget.samples = value;
  76907. },
  76908. enumerable: true,
  76909. configurable: true
  76910. });
  76911. /**
  76912. * Disposes the renderer and frees up associated resources.
  76913. */
  76914. GeometryBufferRenderer.prototype.dispose = function () {
  76915. this.getGBuffer().dispose();
  76916. };
  76917. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76918. var _this = this;
  76919. var engine = this._scene.getEngine();
  76920. var count = this._enablePosition ? 3 : 2;
  76921. 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 });
  76922. if (!this.isSupported) {
  76923. return;
  76924. }
  76925. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76926. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76927. this._multiRenderTarget.refreshRate = 1;
  76928. this._multiRenderTarget.renderParticles = false;
  76929. this._multiRenderTarget.renderList = null;
  76930. // set default depth value to 1.0 (far away)
  76931. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76932. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76933. });
  76934. // Custom render function
  76935. var renderSubMesh = function (subMesh) {
  76936. var mesh = subMesh.getRenderingMesh();
  76937. var scene = _this._scene;
  76938. var engine = scene.getEngine();
  76939. var material = subMesh.getMaterial();
  76940. if (!material) {
  76941. return;
  76942. }
  76943. // Culling
  76944. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76945. // Managing instances
  76946. var batch = mesh._getInstancesRenderList(subMesh._id);
  76947. if (batch.mustReturn) {
  76948. return;
  76949. }
  76950. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76951. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76952. engine.enableEffect(_this._effect);
  76953. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76954. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76955. _this._effect.setMatrix("view", scene.getViewMatrix());
  76956. // Alpha test
  76957. if (material && material.needAlphaTesting()) {
  76958. var alphaTexture = material.getAlphaTestTexture();
  76959. if (alphaTexture) {
  76960. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76961. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76962. }
  76963. }
  76964. // Bones
  76965. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76966. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76967. }
  76968. // Draw
  76969. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76970. }
  76971. };
  76972. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76973. var index;
  76974. if (depthOnlySubMeshes.length) {
  76975. engine.setColorWrite(false);
  76976. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76977. renderSubMesh(depthOnlySubMeshes.data[index]);
  76978. }
  76979. engine.setColorWrite(true);
  76980. }
  76981. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76982. renderSubMesh(opaqueSubMeshes.data[index]);
  76983. }
  76984. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76985. renderSubMesh(alphaTestSubMeshes.data[index]);
  76986. }
  76987. };
  76988. };
  76989. return GeometryBufferRenderer;
  76990. }());
  76991. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76992. })(BABYLON || (BABYLON = {}));
  76993. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76994. var BABYLON;
  76995. (function (BABYLON) {
  76996. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  76997. get: function () {
  76998. this._geometryBufferRenderer;
  76999. },
  77000. set: function (value) {
  77001. if (value && value.isSupported) {
  77002. this._geometryBufferRenderer = value;
  77003. }
  77004. ;
  77005. },
  77006. enumerable: true,
  77007. configurable: true
  77008. });
  77009. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  77010. if (ratio === void 0) { ratio = 1; }
  77011. if (this._geometryBufferRenderer) {
  77012. return this._geometryBufferRenderer;
  77013. }
  77014. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  77015. if (!this._geometryBufferRenderer.isSupported) {
  77016. this._geometryBufferRenderer = null;
  77017. }
  77018. return this._geometryBufferRenderer;
  77019. };
  77020. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  77021. if (!this._geometryBufferRenderer) {
  77022. return;
  77023. }
  77024. this._geometryBufferRenderer.dispose();
  77025. this._geometryBufferRenderer = null;
  77026. };
  77027. /**
  77028. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  77029. * in several rendering techniques.
  77030. */
  77031. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  77032. /**
  77033. * Creates a new instance of the component for the given scene
  77034. * @param scene Defines the scene to register the component in
  77035. */
  77036. function GeometryBufferRendererSceneComponent(scene) {
  77037. /**
  77038. * The component name helpfull to identify the component in the list of scene components.
  77039. */
  77040. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  77041. this.scene = scene;
  77042. }
  77043. /**
  77044. * Registers the component in a given scene
  77045. */
  77046. GeometryBufferRendererSceneComponent.prototype.register = function () {
  77047. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  77048. };
  77049. /**
  77050. * Rebuilds the elements related to this component in case of
  77051. * context lost for instance.
  77052. */
  77053. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  77054. // Nothing to do for this component
  77055. };
  77056. /**
  77057. * Disposes the component and the associated ressources
  77058. */
  77059. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  77060. // Nothing to do for this component
  77061. };
  77062. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77063. if (this.scene._geometryBufferRenderer) {
  77064. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  77065. }
  77066. };
  77067. return GeometryBufferRendererSceneComponent;
  77068. }());
  77069. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  77070. })(BABYLON || (BABYLON = {}));
  77071. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  77072. var BABYLON;
  77073. (function (BABYLON) {
  77074. var SSAORenderingPipeline = /** @class */ (function (_super) {
  77075. __extends(SSAORenderingPipeline, _super);
  77076. /**
  77077. * @constructor
  77078. * @param {string} name - The rendering pipeline name
  77079. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77080. * @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 }
  77081. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77082. */
  77083. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  77084. var _this = _super.call(this, scene.getEngine(), name) || this;
  77085. // Members
  77086. /**
  77087. * The PassPostProcess id in the pipeline that contains the original scene color
  77088. */
  77089. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77090. /**
  77091. * The SSAO PostProcess id in the pipeline
  77092. */
  77093. _this.SSAORenderEffect = "SSAORenderEffect";
  77094. /**
  77095. * The horizontal blur PostProcess id in the pipeline
  77096. */
  77097. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77098. /**
  77099. * The vertical blur PostProcess id in the pipeline
  77100. */
  77101. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77102. /**
  77103. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77104. */
  77105. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77106. /**
  77107. * The output strength of the SSAO post-process. Default value is 1.0.
  77108. */
  77109. _this.totalStrength = 1.0;
  77110. /**
  77111. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  77112. */
  77113. _this.radius = 0.0001;
  77114. /**
  77115. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  77116. * Must not be equal to fallOff and superior to fallOff.
  77117. * Default value is 0.975
  77118. */
  77119. _this.area = 0.0075;
  77120. /**
  77121. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  77122. * Must not be equal to area and inferior to area.
  77123. * Default value is 0.0
  77124. */
  77125. _this.fallOff = 0.000001;
  77126. /**
  77127. * The base color of the SSAO post-process
  77128. * The final result is "base + ssao" between [0, 1]
  77129. */
  77130. _this.base = 0.5;
  77131. _this._firstUpdate = true;
  77132. _this._scene = scene;
  77133. // Set up assets
  77134. _this._createRandomTexture();
  77135. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77136. var ssaoRatio = ratio.ssaoRatio || ratio;
  77137. var combineRatio = ratio.combineRatio || ratio;
  77138. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77139. _this._createSSAOPostProcess(ssaoRatio);
  77140. _this._createBlurPostProcess(ssaoRatio);
  77141. _this._createSSAOCombinePostProcess(combineRatio);
  77142. // Set up pipeline
  77143. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77144. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77145. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77146. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77147. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77148. // Finish
  77149. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77150. if (cameras)
  77151. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77152. return _this;
  77153. }
  77154. // Public Methods
  77155. /**
  77156. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77157. */
  77158. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77159. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77160. for (var i = 0; i < this._scene.cameras.length; i++) {
  77161. var camera = this._scene.cameras[i];
  77162. this._originalColorPostProcess.dispose(camera);
  77163. this._ssaoPostProcess.dispose(camera);
  77164. this._blurHPostProcess.dispose(camera);
  77165. this._blurVPostProcess.dispose(camera);
  77166. this._ssaoCombinePostProcess.dispose(camera);
  77167. }
  77168. this._randomTexture.dispose();
  77169. if (disableDepthRender)
  77170. this._scene.disableDepthRenderer();
  77171. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77172. _super.prototype.dispose.call(this);
  77173. };
  77174. // Private Methods
  77175. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  77176. var _this = this;
  77177. var size = 16;
  77178. 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);
  77179. 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);
  77180. this._blurHPostProcess.onActivateObservable.add(function () {
  77181. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  77182. _this._blurHPostProcess.kernel = size * dw;
  77183. });
  77184. this._blurVPostProcess.onActivateObservable.add(function () {
  77185. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  77186. _this._blurVPostProcess.kernel = size * dw;
  77187. });
  77188. };
  77189. /** @hidden */
  77190. SSAORenderingPipeline.prototype._rebuild = function () {
  77191. this._firstUpdate = true;
  77192. _super.prototype._rebuild.call(this);
  77193. };
  77194. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77195. var _this = this;
  77196. var numSamples = 16;
  77197. var sampleSphere = [
  77198. 0.5381, 0.1856, -0.4319,
  77199. 0.1379, 0.2486, 0.4430,
  77200. 0.3371, 0.5679, -0.0057,
  77201. -0.6999, -0.0451, -0.0019,
  77202. 0.0689, -0.1598, -0.8547,
  77203. 0.0560, 0.0069, -0.1843,
  77204. -0.0146, 0.1402, 0.0762,
  77205. 0.0100, -0.1924, -0.0344,
  77206. -0.3577, -0.5301, -0.4358,
  77207. -0.3169, 0.1063, 0.0158,
  77208. 0.0103, -0.5869, 0.0046,
  77209. -0.0897, -0.4940, 0.3287,
  77210. 0.7119, -0.0154, -0.0918,
  77211. -0.0533, 0.0596, -0.5411,
  77212. 0.0352, -0.0631, 0.5460,
  77213. -0.4776, 0.2847, -0.0271
  77214. ];
  77215. var samplesFactor = 1.0 / numSamples;
  77216. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  77217. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77218. "area", "fallOff", "base", "range", "viewport"
  77219. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77220. this._ssaoPostProcess.onApply = function (effect) {
  77221. if (_this._firstUpdate) {
  77222. effect.setArray3("sampleSphere", sampleSphere);
  77223. effect.setFloat("samplesFactor", samplesFactor);
  77224. effect.setFloat("randTextureTiles", 4.0);
  77225. }
  77226. effect.setFloat("totalStrength", _this.totalStrength);
  77227. effect.setFloat("radius", _this.radius);
  77228. effect.setFloat("area", _this.area);
  77229. effect.setFloat("fallOff", _this.fallOff);
  77230. effect.setFloat("base", _this.base);
  77231. effect.setTexture("textureSampler", _this._depthTexture);
  77232. effect.setTexture("randomSampler", _this._randomTexture);
  77233. };
  77234. };
  77235. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77236. var _this = this;
  77237. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77238. this._ssaoCombinePostProcess.onApply = function (effect) {
  77239. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  77240. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77241. };
  77242. };
  77243. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  77244. var size = 512;
  77245. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77246. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77247. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77248. var context = this._randomTexture.getContext();
  77249. var rand = function (min, max) {
  77250. return Math.random() * (max - min) + min;
  77251. };
  77252. var randVector = BABYLON.Vector3.Zero();
  77253. for (var x = 0; x < size; x++) {
  77254. for (var y = 0; y < size; y++) {
  77255. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  77256. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  77257. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  77258. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77259. context.fillRect(x, y, 1, 1);
  77260. }
  77261. }
  77262. this._randomTexture.update(false);
  77263. };
  77264. __decorate([
  77265. BABYLON.serialize()
  77266. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  77267. __decorate([
  77268. BABYLON.serialize()
  77269. ], SSAORenderingPipeline.prototype, "radius", void 0);
  77270. __decorate([
  77271. BABYLON.serialize()
  77272. ], SSAORenderingPipeline.prototype, "area", void 0);
  77273. __decorate([
  77274. BABYLON.serialize()
  77275. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  77276. __decorate([
  77277. BABYLON.serialize()
  77278. ], SSAORenderingPipeline.prototype, "base", void 0);
  77279. return SSAORenderingPipeline;
  77280. }(BABYLON.PostProcessRenderPipeline));
  77281. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  77282. })(BABYLON || (BABYLON = {}));
  77283. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  77284. var BABYLON;
  77285. (function (BABYLON) {
  77286. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  77287. __extends(SSAO2RenderingPipeline, _super);
  77288. /**
  77289. * @constructor
  77290. * @param {string} name - The rendering pipeline name
  77291. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77292. * @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 }
  77293. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77294. */
  77295. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  77296. var _this = _super.call(this, scene.getEngine(), name) || this;
  77297. // Members
  77298. /**
  77299. * The PassPostProcess id in the pipeline that contains the original scene color
  77300. */
  77301. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  77302. /**
  77303. * The SSAO PostProcess id in the pipeline
  77304. */
  77305. _this.SSAORenderEffect = "SSAORenderEffect";
  77306. /**
  77307. * The horizontal blur PostProcess id in the pipeline
  77308. */
  77309. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  77310. /**
  77311. * The vertical blur PostProcess id in the pipeline
  77312. */
  77313. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  77314. /**
  77315. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  77316. */
  77317. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  77318. /**
  77319. * The output strength of the SSAO post-process. Default value is 1.0.
  77320. */
  77321. _this.totalStrength = 1.0;
  77322. /**
  77323. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  77324. */
  77325. _this.maxZ = 100.0;
  77326. /**
  77327. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  77328. */
  77329. _this.minZAspect = 0.2;
  77330. _this._samples = 8;
  77331. _this._textureSamples = 1;
  77332. /**
  77333. * Are we using bilateral blur ?
  77334. */
  77335. _this._expensiveBlur = true;
  77336. /**
  77337. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  77338. */
  77339. _this.radius = 2.0;
  77340. /**
  77341. * The base color of the SSAO post-process
  77342. * The final result is "base + ssao" between [0, 1]
  77343. */
  77344. _this.base = 0;
  77345. _this._firstUpdate = true;
  77346. _this._bits = new Uint32Array(1);
  77347. _this._scene = scene;
  77348. _this._ratio = ratio;
  77349. if (!_this.isSupported) {
  77350. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  77351. return _this;
  77352. }
  77353. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  77354. var blurRatio = _this._ratio.blurRatio || ratio;
  77355. // Set up assets
  77356. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  77357. _this._createRandomTexture();
  77358. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  77359. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  77360. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  77361. _this._originalColorPostProcess.samples = _this.textureSamples;
  77362. _this._createSSAOPostProcess(1.0);
  77363. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  77364. _this._createSSAOCombinePostProcess(blurRatio);
  77365. // Set up pipeline
  77366. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  77367. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  77368. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  77369. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  77370. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  77371. // Finish
  77372. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77373. if (cameras)
  77374. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77375. return _this;
  77376. }
  77377. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  77378. get: function () {
  77379. return this._samples;
  77380. },
  77381. /**
  77382. * Number of samples used for the SSAO calculations. Default value is 8
  77383. */
  77384. set: function (n) {
  77385. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  77386. this._samples = n;
  77387. this._sampleSphere = this._generateHemisphere();
  77388. this._firstUpdate = true;
  77389. },
  77390. enumerable: true,
  77391. configurable: true
  77392. });
  77393. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  77394. get: function () {
  77395. return this._textureSamples;
  77396. },
  77397. /**
  77398. * Number of samples to use for antialiasing
  77399. */
  77400. set: function (n) {
  77401. this._textureSamples = n;
  77402. this._originalColorPostProcess.samples = n;
  77403. this._blurHPostProcess.samples = n;
  77404. this._blurVPostProcess.samples = n;
  77405. this._ssaoPostProcess.samples = n;
  77406. this._ssaoCombinePostProcess.samples = n;
  77407. },
  77408. enumerable: true,
  77409. configurable: true
  77410. });
  77411. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  77412. get: function () {
  77413. return this._expensiveBlur;
  77414. },
  77415. set: function (b) {
  77416. 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"]);
  77417. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  77418. this._expensiveBlur = b;
  77419. this._firstUpdate = true;
  77420. },
  77421. enumerable: true,
  77422. configurable: true
  77423. });
  77424. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  77425. /**
  77426. * Support test.
  77427. */
  77428. get: function () {
  77429. var engine = BABYLON.Engine.LastCreatedEngine;
  77430. if (!engine) {
  77431. return false;
  77432. }
  77433. return engine.getCaps().drawBuffersExtension;
  77434. },
  77435. enumerable: true,
  77436. configurable: true
  77437. });
  77438. // Public Methods
  77439. /**
  77440. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  77441. */
  77442. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  77443. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  77444. for (var i = 0; i < this._scene.cameras.length; i++) {
  77445. var camera = this._scene.cameras[i];
  77446. this._originalColorPostProcess.dispose(camera);
  77447. this._ssaoPostProcess.dispose(camera);
  77448. this._blurHPostProcess.dispose(camera);
  77449. this._blurVPostProcess.dispose(camera);
  77450. this._ssaoCombinePostProcess.dispose(camera);
  77451. }
  77452. this._randomTexture.dispose();
  77453. if (disableGeometryBufferRenderer)
  77454. this._scene.disableGeometryBufferRenderer();
  77455. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77456. _super.prototype.dispose.call(this);
  77457. };
  77458. // Private Methods
  77459. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  77460. var _this = this;
  77461. this._samplerOffsets = [];
  77462. var expensive = this.expensiveBlur;
  77463. for (var i = -8; i < 8; i++) {
  77464. this._samplerOffsets.push(i * 2 + 0.5);
  77465. }
  77466. 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");
  77467. this._blurHPostProcess.onApply = function (effect) {
  77468. if (!_this._scene.activeCamera) {
  77469. return;
  77470. }
  77471. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  77472. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77473. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77474. effect.setFloat("radius", _this.radius);
  77475. effect.setTexture("depthSampler", _this._depthTexture);
  77476. if (_this._firstUpdate) {
  77477. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77478. }
  77479. };
  77480. 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");
  77481. this._blurVPostProcess.onApply = function (effect) {
  77482. if (!_this._scene.activeCamera) {
  77483. return;
  77484. }
  77485. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  77486. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77487. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77488. effect.setFloat("radius", _this.radius);
  77489. effect.setTexture("depthSampler", _this._depthTexture);
  77490. if (_this._firstUpdate) {
  77491. effect.setArray("samplerOffsets", _this._samplerOffsets);
  77492. _this._firstUpdate = false;
  77493. }
  77494. };
  77495. this._blurHPostProcess.samples = this.textureSamples;
  77496. this._blurVPostProcess.samples = this.textureSamples;
  77497. };
  77498. /** @hidden */
  77499. SSAO2RenderingPipeline.prototype._rebuild = function () {
  77500. this._firstUpdate = true;
  77501. _super.prototype._rebuild.call(this);
  77502. };
  77503. //Van der Corput radical inverse
  77504. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  77505. this._bits[0] = i;
  77506. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  77507. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  77508. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  77509. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  77510. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  77511. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  77512. };
  77513. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  77514. return [i / n, this._radicalInverse_VdC(i)];
  77515. };
  77516. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  77517. var phi = v * 2.0 * Math.PI;
  77518. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  77519. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  77520. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  77521. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  77522. };
  77523. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  77524. var numSamples = this.samples;
  77525. var result = [];
  77526. var vector;
  77527. var i = 0;
  77528. while (i < numSamples) {
  77529. if (numSamples < 16) {
  77530. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  77531. }
  77532. else {
  77533. var rand = this._hammersley(i, numSamples);
  77534. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  77535. }
  77536. result.push(vector.x, vector.y, vector.z);
  77537. i++;
  77538. }
  77539. return result;
  77540. };
  77541. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  77542. var _this = this;
  77543. var numSamples = this.samples;
  77544. this._sampleSphere = this._generateHemisphere();
  77545. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  77546. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  77547. "base", "range", "projection", "near", "far", "texelSize",
  77548. "xViewport", "yViewport", "maxZ", "minZAspect"
  77549. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  77550. this._ssaoPostProcess.onApply = function (effect) {
  77551. if (_this._firstUpdate) {
  77552. effect.setArray3("sampleSphere", _this._sampleSphere);
  77553. effect.setFloat("randTextureTiles", 32.0);
  77554. }
  77555. if (!_this._scene.activeCamera) {
  77556. return;
  77557. }
  77558. effect.setFloat("samplesFactor", 1 / _this.samples);
  77559. effect.setFloat("totalStrength", _this.totalStrength);
  77560. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  77561. effect.setFloat("radius", _this.radius);
  77562. effect.setFloat("maxZ", _this.maxZ);
  77563. effect.setFloat("minZAspect", _this.minZAspect);
  77564. effect.setFloat("base", _this.base);
  77565. effect.setFloat("near", _this._scene.activeCamera.minZ);
  77566. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  77567. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  77568. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  77569. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  77570. effect.setTexture("textureSampler", _this._depthTexture);
  77571. effect.setTexture("normalSampler", _this._normalTexture);
  77572. effect.setTexture("randomSampler", _this._randomTexture);
  77573. };
  77574. this._ssaoPostProcess.samples = this.textureSamples;
  77575. };
  77576. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  77577. var _this = this;
  77578. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77579. this._ssaoCombinePostProcess.onApply = function (effect) {
  77580. var viewport = _this._scene.activeCamera.viewport;
  77581. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  77582. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  77583. };
  77584. this._ssaoCombinePostProcess.samples = this.textureSamples;
  77585. };
  77586. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  77587. var size = 128;
  77588. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77589. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77590. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77591. var context = this._randomTexture.getContext();
  77592. var rand = function (min, max) {
  77593. return Math.random() * (max - min) + min;
  77594. };
  77595. var randVector = BABYLON.Vector3.Zero();
  77596. for (var x = 0; x < size; x++) {
  77597. for (var y = 0; y < size; y++) {
  77598. randVector.x = rand(0.0, 1.0);
  77599. randVector.y = rand(0.0, 1.0);
  77600. randVector.z = 0.0;
  77601. randVector.normalize();
  77602. randVector.scaleInPlace(255);
  77603. randVector.x = Math.floor(randVector.x);
  77604. randVector.y = Math.floor(randVector.y);
  77605. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  77606. context.fillRect(x, y, 1, 1);
  77607. }
  77608. }
  77609. this._randomTexture.update(false);
  77610. };
  77611. /**
  77612. * Serialize the rendering pipeline (Used when exporting)
  77613. * @returns the serialized object
  77614. */
  77615. SSAO2RenderingPipeline.prototype.serialize = function () {
  77616. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77617. serializationObject.customType = "SSAO2RenderingPipeline";
  77618. return serializationObject;
  77619. };
  77620. /**
  77621. * Parse the serialized pipeline
  77622. * @param source Source pipeline.
  77623. * @param scene The scene to load the pipeline to.
  77624. * @param rootUrl The URL of the serialized pipeline.
  77625. * @returns An instantiated pipeline from the serialized object.
  77626. */
  77627. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  77628. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77629. };
  77630. __decorate([
  77631. BABYLON.serialize()
  77632. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  77633. __decorate([
  77634. BABYLON.serialize()
  77635. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  77636. __decorate([
  77637. BABYLON.serialize()
  77638. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  77639. __decorate([
  77640. BABYLON.serialize("samples")
  77641. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  77642. __decorate([
  77643. BABYLON.serialize("textureSamples")
  77644. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  77645. __decorate([
  77646. BABYLON.serialize()
  77647. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  77648. __decorate([
  77649. BABYLON.serialize("expensiveBlur")
  77650. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  77651. __decorate([
  77652. BABYLON.serialize()
  77653. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  77654. __decorate([
  77655. BABYLON.serialize()
  77656. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  77657. return SSAO2RenderingPipeline;
  77658. }(BABYLON.PostProcessRenderPipeline));
  77659. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  77660. })(BABYLON || (BABYLON = {}));
  77661. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  77662. // BABYLON.JS Chromatic Aberration GLSL Shader
  77663. // Author: Olivier Guyot
  77664. // Separates very slightly R, G and B colors on the edges of the screen
  77665. // Inspired by Francois Tarlier & Martins Upitis
  77666. var BABYLON;
  77667. (function (BABYLON) {
  77668. var LensRenderingPipeline = /** @class */ (function (_super) {
  77669. __extends(LensRenderingPipeline, _super);
  77670. /**
  77671. * @constructor
  77672. *
  77673. * Effect parameters are as follow:
  77674. * {
  77675. * chromatic_aberration: number; // from 0 to x (1 for realism)
  77676. * edge_blur: number; // from 0 to x (1 for realism)
  77677. * distortion: number; // from 0 to x (1 for realism)
  77678. * grain_amount: number; // from 0 to 1
  77679. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  77680. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  77681. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  77682. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  77683. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  77684. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  77685. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  77686. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  77687. * }
  77688. * Note: if an effect parameter is unset, effect is disabled
  77689. *
  77690. * @param {string} name - The rendering pipeline name
  77691. * @param {object} parameters - An object containing all parameters (see above)
  77692. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77693. * @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)
  77694. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77695. */
  77696. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  77697. if (ratio === void 0) { ratio = 1.0; }
  77698. var _this = _super.call(this, scene.getEngine(), name) || this;
  77699. // Lens effects can be of the following:
  77700. // - chromatic aberration (slight shift of RGB colors)
  77701. // - blur on the edge of the lens
  77702. // - lens distortion
  77703. // - depth-of-field blur & highlights enhancing
  77704. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  77705. // - grain effect (noise or custom texture)
  77706. // Two additional texture samplers are needed:
  77707. // - depth map (for depth-of-field)
  77708. // - grain texture
  77709. /**
  77710. * The chromatic aberration PostProcess id in the pipeline
  77711. */
  77712. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  77713. /**
  77714. * The highlights enhancing PostProcess id in the pipeline
  77715. */
  77716. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  77717. /**
  77718. * The depth-of-field PostProcess id in the pipeline
  77719. */
  77720. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  77721. _this._scene = scene;
  77722. // Fetch texture samplers
  77723. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  77724. if (parameters.grain_texture) {
  77725. _this._grainTexture = parameters.grain_texture;
  77726. }
  77727. else {
  77728. _this._createGrainTexture();
  77729. }
  77730. // save parameters
  77731. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  77732. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  77733. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  77734. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  77735. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  77736. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  77737. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  77738. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  77739. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  77740. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  77741. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  77742. // Create effects
  77743. _this._createChromaticAberrationPostProcess(ratio);
  77744. _this._createHighlightsPostProcess(ratio);
  77745. _this._createDepthOfFieldPostProcess(ratio / 4);
  77746. // Set up pipeline
  77747. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  77748. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  77749. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  77750. if (_this._highlightsGain === -1) {
  77751. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  77752. }
  77753. // Finish
  77754. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77755. if (cameras) {
  77756. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  77757. }
  77758. return _this;
  77759. }
  77760. // public methods (self explanatory)
  77761. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  77762. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  77763. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  77764. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  77765. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  77766. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  77767. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  77768. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  77769. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  77770. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  77771. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  77772. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  77773. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  77774. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  77775. };
  77776. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  77777. this._highlightsPostProcess.updateEffect();
  77778. };
  77779. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  77780. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  77781. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  77782. this._highlightsGain = amount;
  77783. };
  77784. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  77785. if (this._highlightsGain === -1) {
  77786. this._highlightsGain = 1.0;
  77787. }
  77788. this._highlightsThreshold = amount;
  77789. };
  77790. LensRenderingPipeline.prototype.disableHighlights = function () {
  77791. this._highlightsGain = -1;
  77792. };
  77793. /**
  77794. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  77795. */
  77796. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77797. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77798. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77799. this._chromaticAberrationPostProcess = null;
  77800. this._highlightsPostProcess = null;
  77801. this._depthOfFieldPostProcess = null;
  77802. this._grainTexture.dispose();
  77803. if (disableDepthRender)
  77804. this._scene.disableDepthRenderer();
  77805. };
  77806. // colors shifting and distortion
  77807. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  77808. var _this = this;
  77809. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  77810. [], // samplers
  77811. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77812. this._chromaticAberrationPostProcess.onApply = function (effect) {
  77813. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  77814. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77815. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77816. effect.setFloat('radialIntensity', 1);
  77817. effect.setFloat2('direction', 17, 17);
  77818. effect.setFloat2('centerPosition', 0.5, 0.5);
  77819. };
  77820. };
  77821. // highlights enhancing
  77822. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  77823. var _this = this;
  77824. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  77825. [], // samplers
  77826. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  77827. this._highlightsPostProcess.onApply = function (effect) {
  77828. effect.setFloat('gain', _this._highlightsGain);
  77829. effect.setFloat('threshold', _this._highlightsThreshold);
  77830. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  77831. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77832. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77833. };
  77834. };
  77835. // colors shifting and distortion
  77836. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  77837. var _this = this;
  77838. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  77839. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  77840. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  77841. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77842. this._depthOfFieldPostProcess.onApply = function (effect) {
  77843. effect.setTexture("depthSampler", _this._depthTexture);
  77844. effect.setTexture("grainSampler", _this._grainTexture);
  77845. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  77846. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  77847. effect.setFloat('grain_amount', _this._grainAmount);
  77848. effect.setBool('blur_noise', _this._blurNoise);
  77849. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77850. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77851. effect.setFloat('distortion', _this._distortion);
  77852. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  77853. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  77854. effect.setFloat('aperture', _this._dofAperture);
  77855. effect.setFloat('darken', _this._dofDarken);
  77856. effect.setFloat('edge_blur', _this._edgeBlur);
  77857. effect.setBool('highlights', (_this._highlightsGain !== -1));
  77858. if (_this._scene.activeCamera) {
  77859. effect.setFloat('near', _this._scene.activeCamera.minZ);
  77860. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  77861. }
  77862. };
  77863. };
  77864. // creates a black and white random noise texture, 512x512
  77865. LensRenderingPipeline.prototype._createGrainTexture = function () {
  77866. var size = 512;
  77867. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77868. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77869. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77870. var context = this._grainTexture.getContext();
  77871. var rand = function (min, max) {
  77872. return Math.random() * (max - min) + min;
  77873. };
  77874. var value;
  77875. for (var x = 0; x < size; x++) {
  77876. for (var y = 0; y < size; y++) {
  77877. value = Math.floor(rand(0.42, 0.58) * 255);
  77878. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  77879. context.fillRect(x, y, 1, 1);
  77880. }
  77881. }
  77882. this._grainTexture.update(false);
  77883. };
  77884. return LensRenderingPipeline;
  77885. }(BABYLON.PostProcessRenderPipeline));
  77886. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  77887. })(BABYLON || (BABYLON = {}));
  77888. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  77889. var BABYLON;
  77890. (function (BABYLON) {
  77891. var StandardRenderingPipeline = /** @class */ (function (_super) {
  77892. __extends(StandardRenderingPipeline, _super);
  77893. /**
  77894. * @constructor
  77895. * @param {string} name - The rendering pipeline name
  77896. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77897. * @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)
  77898. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  77899. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77900. */
  77901. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  77902. if (originalPostProcess === void 0) { originalPostProcess = null; }
  77903. var _this = _super.call(this, scene.getEngine(), name) || this;
  77904. _this.downSampleX4PostProcess = null;
  77905. _this.brightPassPostProcess = null;
  77906. _this.blurHPostProcesses = [];
  77907. _this.blurVPostProcesses = [];
  77908. _this.textureAdderPostProcess = null;
  77909. _this.volumetricLightPostProcess = null;
  77910. _this.volumetricLightSmoothXPostProcess = null;
  77911. _this.volumetricLightSmoothYPostProcess = null;
  77912. _this.volumetricLightMergePostProces = null;
  77913. _this.volumetricLightFinalPostProcess = null;
  77914. _this.luminancePostProcess = null;
  77915. _this.luminanceDownSamplePostProcesses = [];
  77916. _this.hdrPostProcess = null;
  77917. _this.textureAdderFinalPostProcess = null;
  77918. _this.lensFlareFinalPostProcess = null;
  77919. _this.hdrFinalPostProcess = null;
  77920. _this.lensFlarePostProcess = null;
  77921. _this.lensFlareComposePostProcess = null;
  77922. _this.motionBlurPostProcess = null;
  77923. _this.depthOfFieldPostProcess = null;
  77924. // Values
  77925. _this.brightThreshold = 1.0;
  77926. _this.blurWidth = 512.0;
  77927. _this.horizontalBlur = false;
  77928. _this.exposure = 1.0;
  77929. _this.lensTexture = null;
  77930. _this.volumetricLightCoefficient = 0.2;
  77931. _this.volumetricLightPower = 4.0;
  77932. _this.volumetricLightBlurScale = 64.0;
  77933. _this.sourceLight = null;
  77934. _this.hdrMinimumLuminance = 1.0;
  77935. _this.hdrDecreaseRate = 0.5;
  77936. _this.hdrIncreaseRate = 0.5;
  77937. _this.lensColorTexture = null;
  77938. _this.lensFlareStrength = 20.0;
  77939. _this.lensFlareGhostDispersal = 1.4;
  77940. _this.lensFlareHaloWidth = 0.7;
  77941. _this.lensFlareDistortionStrength = 16.0;
  77942. _this.lensStarTexture = null;
  77943. _this.lensFlareDirtTexture = null;
  77944. _this.depthOfFieldDistance = 10.0;
  77945. _this.depthOfFieldBlurWidth = 64.0;
  77946. _this.motionStrength = 1.0;
  77947. // IAnimatable
  77948. _this.animations = [];
  77949. _this._currentDepthOfFieldSource = null;
  77950. _this._hdrCurrentLuminance = 1.0;
  77951. // Getters and setters
  77952. _this._bloomEnabled = true;
  77953. _this._depthOfFieldEnabled = false;
  77954. _this._vlsEnabled = false;
  77955. _this._lensFlareEnabled = false;
  77956. _this._hdrEnabled = false;
  77957. _this._motionBlurEnabled = false;
  77958. _this._motionBlurSamples = 64.0;
  77959. _this._volumetricLightStepsCount = 50.0;
  77960. _this._cameras = cameras || [];
  77961. // Initialize
  77962. _this._scene = scene;
  77963. _this._basePostProcess = originalPostProcess;
  77964. _this._ratio = ratio;
  77965. // Misc
  77966. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77967. // Finish
  77968. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77969. _this._buildPipeline();
  77970. return _this;
  77971. }
  77972. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  77973. get: function () {
  77974. return this._bloomEnabled;
  77975. },
  77976. set: function (enabled) {
  77977. if (this._bloomEnabled === enabled) {
  77978. return;
  77979. }
  77980. this._bloomEnabled = enabled;
  77981. this._buildPipeline();
  77982. },
  77983. enumerable: true,
  77984. configurable: true
  77985. });
  77986. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  77987. get: function () {
  77988. return this._depthOfFieldEnabled;
  77989. },
  77990. set: function (enabled) {
  77991. if (this._depthOfFieldEnabled === enabled) {
  77992. return;
  77993. }
  77994. this._depthOfFieldEnabled = enabled;
  77995. this._buildPipeline();
  77996. },
  77997. enumerable: true,
  77998. configurable: true
  77999. });
  78000. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  78001. get: function () {
  78002. return this._lensFlareEnabled;
  78003. },
  78004. set: function (enabled) {
  78005. if (this._lensFlareEnabled === enabled) {
  78006. return;
  78007. }
  78008. this._lensFlareEnabled = enabled;
  78009. this._buildPipeline();
  78010. },
  78011. enumerable: true,
  78012. configurable: true
  78013. });
  78014. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  78015. get: function () {
  78016. return this._hdrEnabled;
  78017. },
  78018. set: function (enabled) {
  78019. if (this._hdrEnabled === enabled) {
  78020. return;
  78021. }
  78022. this._hdrEnabled = enabled;
  78023. this._buildPipeline();
  78024. },
  78025. enumerable: true,
  78026. configurable: true
  78027. });
  78028. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  78029. get: function () {
  78030. return this._vlsEnabled;
  78031. },
  78032. set: function (enabled) {
  78033. if (this._vlsEnabled === enabled) {
  78034. return;
  78035. }
  78036. if (enabled) {
  78037. var geometry = this._scene.enableGeometryBufferRenderer();
  78038. if (!geometry) {
  78039. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  78040. return;
  78041. }
  78042. }
  78043. this._vlsEnabled = enabled;
  78044. this._buildPipeline();
  78045. },
  78046. enumerable: true,
  78047. configurable: true
  78048. });
  78049. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  78050. get: function () {
  78051. return this._motionBlurEnabled;
  78052. },
  78053. set: function (enabled) {
  78054. if (this._motionBlurEnabled === enabled) {
  78055. return;
  78056. }
  78057. this._motionBlurEnabled = enabled;
  78058. this._buildPipeline();
  78059. },
  78060. enumerable: true,
  78061. configurable: true
  78062. });
  78063. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  78064. get: function () {
  78065. return this._volumetricLightStepsCount;
  78066. },
  78067. set: function (count) {
  78068. if (this.volumetricLightPostProcess) {
  78069. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  78070. }
  78071. this._volumetricLightStepsCount = count;
  78072. },
  78073. enumerable: true,
  78074. configurable: true
  78075. });
  78076. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  78077. get: function () {
  78078. return this._motionBlurSamples;
  78079. },
  78080. set: function (samples) {
  78081. if (this.motionBlurPostProcess) {
  78082. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  78083. }
  78084. this._motionBlurSamples = samples;
  78085. },
  78086. enumerable: true,
  78087. configurable: true
  78088. });
  78089. StandardRenderingPipeline.prototype._buildPipeline = function () {
  78090. var _this = this;
  78091. var ratio = this._ratio;
  78092. var scene = this._scene;
  78093. this._disposePostProcesses();
  78094. this._reset();
  78095. // Create pass post-process
  78096. if (!this._basePostProcess) {
  78097. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  78098. this.originalPostProcess.onApply = function (effect) {
  78099. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  78100. };
  78101. }
  78102. else {
  78103. this.originalPostProcess = this._basePostProcess;
  78104. }
  78105. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  78106. this._currentDepthOfFieldSource = this.originalPostProcess;
  78107. if (this._bloomEnabled) {
  78108. // Create down sample X4 post-process
  78109. this._createDownSampleX4PostProcess(scene, ratio / 2);
  78110. // Create bright pass post-process
  78111. this._createBrightPassPostProcess(scene, ratio / 2);
  78112. // Create gaussian blur post-processes (down sampling blurs)
  78113. this._createBlurPostProcesses(scene, ratio / 4, 1);
  78114. // Create texture adder post-process
  78115. this._createTextureAdderPostProcess(scene, ratio);
  78116. // Create depth-of-field source post-process
  78117. 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);
  78118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  78119. }
  78120. if (this._vlsEnabled) {
  78121. // Create volumetric light
  78122. this._createVolumetricLightPostProcess(scene, ratio);
  78123. // Create volumetric light final post-process
  78124. 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);
  78125. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  78126. }
  78127. if (this._lensFlareEnabled) {
  78128. // Create lens flare post-process
  78129. this._createLensFlarePostProcess(scene, ratio);
  78130. // Create depth-of-field source post-process post lens-flare and disable it now
  78131. 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);
  78132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  78133. }
  78134. if (this._hdrEnabled) {
  78135. // Create luminance
  78136. this._createLuminancePostProcesses(scene, this._floatTextureType);
  78137. // Create HDR
  78138. this._createHdrPostProcess(scene, ratio);
  78139. // Create depth-of-field source post-process post hdr and disable it now
  78140. 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);
  78141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  78142. }
  78143. if (this._depthOfFieldEnabled) {
  78144. // Create gaussian blur used by depth-of-field
  78145. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  78146. // Create depth-of-field post-process
  78147. this._createDepthOfFieldPostProcess(scene, ratio);
  78148. }
  78149. if (this._motionBlurEnabled) {
  78150. // Create motion blur post-process
  78151. this._createMotionBlurPostProcess(scene, ratio);
  78152. }
  78153. if (this._cameras !== null) {
  78154. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78155. }
  78156. };
  78157. // Down Sample X4 Post-Processs
  78158. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  78159. var _this = this;
  78160. var downSampleX4Offsets = new Array(32);
  78161. 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);
  78162. this.downSampleX4PostProcess.onApply = function (effect) {
  78163. var id = 0;
  78164. var width = _this.downSampleX4PostProcess.width;
  78165. var height = _this.downSampleX4PostProcess.height;
  78166. for (var i = -2; i < 2; i++) {
  78167. for (var j = -2; j < 2; j++) {
  78168. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  78169. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  78170. id += 2;
  78171. }
  78172. }
  78173. effect.setArray2("dsOffsets", downSampleX4Offsets);
  78174. };
  78175. // Add to pipeline
  78176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  78177. };
  78178. // Brightpass Post-Process
  78179. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  78180. var _this = this;
  78181. var brightOffsets = new Array(8);
  78182. 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);
  78183. this.brightPassPostProcess.onApply = function (effect) {
  78184. var sU = (1.0 / _this.brightPassPostProcess.width);
  78185. var sV = (1.0 / _this.brightPassPostProcess.height);
  78186. brightOffsets[0] = -0.5 * sU;
  78187. brightOffsets[1] = 0.5 * sV;
  78188. brightOffsets[2] = 0.5 * sU;
  78189. brightOffsets[3] = 0.5 * sV;
  78190. brightOffsets[4] = -0.5 * sU;
  78191. brightOffsets[5] = -0.5 * sV;
  78192. brightOffsets[6] = 0.5 * sU;
  78193. brightOffsets[7] = -0.5 * sV;
  78194. effect.setArray2("dsOffsets", brightOffsets);
  78195. effect.setFloat("brightThreshold", _this.brightThreshold);
  78196. };
  78197. // Add to pipeline
  78198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  78199. };
  78200. // Create blur H&V post-processes
  78201. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  78202. var _this = this;
  78203. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  78204. var engine = scene.getEngine();
  78205. 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);
  78206. 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);
  78207. blurX.onActivateObservable.add(function () {
  78208. var dw = blurX.width / engine.getRenderWidth();
  78209. blurX.kernel = _this[blurWidthKey] * dw;
  78210. });
  78211. blurY.onActivateObservable.add(function () {
  78212. var dw = blurY.height / engine.getRenderHeight();
  78213. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  78214. });
  78215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  78216. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  78217. this.blurHPostProcesses.push(blurX);
  78218. this.blurVPostProcesses.push(blurY);
  78219. };
  78220. // Create texture adder post-process
  78221. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  78222. var _this = this;
  78223. 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);
  78224. this.textureAdderPostProcess.onApply = function (effect) {
  78225. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  78226. effect.setTexture("lensSampler", _this.lensTexture);
  78227. effect.setFloat("exposure", _this.exposure);
  78228. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  78229. };
  78230. // Add to pipeline
  78231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  78232. };
  78233. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  78234. var _this = this;
  78235. var geometryRenderer = scene.enableGeometryBufferRenderer();
  78236. geometryRenderer.enablePosition = true;
  78237. var geometry = geometryRenderer.getGBuffer();
  78238. // Base post-process
  78239. 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));
  78240. var depthValues = BABYLON.Vector2.Zero();
  78241. this.volumetricLightPostProcess.onApply = function (effect) {
  78242. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  78243. var generator = _this.sourceLight.getShadowGenerator();
  78244. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  78245. effect.setTexture("positionSampler", geometry.textures[2]);
  78246. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  78247. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  78248. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  78249. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  78250. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  78251. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  78252. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  78253. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  78254. effect.setVector2("depthValues", depthValues);
  78255. }
  78256. };
  78257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  78258. // Smooth
  78259. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  78260. // Merge
  78261. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  78262. this.volumetricLightMergePostProces.onApply = function (effect) {
  78263. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  78264. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  78265. };
  78266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  78267. };
  78268. // Create luminance
  78269. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  78270. var _this = this;
  78271. // Create luminance
  78272. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  78273. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  78274. var offsets = [];
  78275. this.luminancePostProcess.onApply = function (effect) {
  78276. var sU = (1.0 / _this.luminancePostProcess.width);
  78277. var sV = (1.0 / _this.luminancePostProcess.height);
  78278. offsets[0] = -0.5 * sU;
  78279. offsets[1] = 0.5 * sV;
  78280. offsets[2] = 0.5 * sU;
  78281. offsets[3] = 0.5 * sV;
  78282. offsets[4] = -0.5 * sU;
  78283. offsets[5] = -0.5 * sV;
  78284. offsets[6] = 0.5 * sU;
  78285. offsets[7] = -0.5 * sV;
  78286. effect.setArray2("lumOffsets", offsets);
  78287. };
  78288. // Add to pipeline
  78289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  78290. // Create down sample luminance
  78291. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  78292. var size = Math.pow(3, i);
  78293. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  78294. if (i === 0) {
  78295. defines += "#define FINAL_DOWN_SAMPLER";
  78296. }
  78297. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  78298. this.luminanceDownSamplePostProcesses.push(postProcess);
  78299. }
  78300. // Create callbacks and add effects
  78301. var lastLuminance = this.luminancePostProcess;
  78302. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  78303. var downSampleOffsets = new Array(18);
  78304. pp.onApply = function (effect) {
  78305. if (!lastLuminance) {
  78306. return;
  78307. }
  78308. var id = 0;
  78309. for (var x = -1; x < 2; x++) {
  78310. for (var y = -1; y < 2; y++) {
  78311. downSampleOffsets[id] = x / lastLuminance.width;
  78312. downSampleOffsets[id + 1] = y / lastLuminance.height;
  78313. id += 2;
  78314. }
  78315. }
  78316. effect.setArray2("dsOffsets", downSampleOffsets);
  78317. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  78318. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78319. lastLuminance = _this.luminancePostProcess;
  78320. }
  78321. else {
  78322. lastLuminance = pp;
  78323. }
  78324. };
  78325. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  78326. pp.onAfterRender = function (effect) {
  78327. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  78328. 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);
  78329. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  78330. };
  78331. }
  78332. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  78333. });
  78334. };
  78335. // Create HDR post-process
  78336. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  78337. var _this = this;
  78338. 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);
  78339. var outputLiminance = 1;
  78340. var time = 0;
  78341. var lastTime = 0;
  78342. this.hdrPostProcess.onApply = function (effect) {
  78343. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  78344. time += scene.getEngine().getDeltaTime();
  78345. if (outputLiminance < 0) {
  78346. outputLiminance = _this._hdrCurrentLuminance;
  78347. }
  78348. else {
  78349. var dt = (lastTime - time) / 1000.0;
  78350. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  78351. outputLiminance += _this.hdrDecreaseRate * dt;
  78352. }
  78353. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  78354. outputLiminance -= _this.hdrIncreaseRate * dt;
  78355. }
  78356. else {
  78357. outputLiminance = _this._hdrCurrentLuminance;
  78358. }
  78359. }
  78360. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  78361. effect.setFloat("averageLuminance", outputLiminance);
  78362. lastTime = time;
  78363. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  78364. };
  78365. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  78366. };
  78367. // Create lens flare post-process
  78368. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  78369. var _this = this;
  78370. 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);
  78371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  78372. this._createBlurPostProcesses(scene, ratio / 4, 2);
  78373. 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);
  78374. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  78375. var resolution = new BABYLON.Vector2(0, 0);
  78376. // Lens flare
  78377. this.lensFlarePostProcess.onApply = function (effect) {
  78378. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  78379. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  78380. effect.setFloat("strength", _this.lensFlareStrength);
  78381. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  78382. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  78383. // Shift
  78384. resolution.x = _this.lensFlarePostProcess.width;
  78385. resolution.y = _this.lensFlarePostProcess.height;
  78386. effect.setVector2("resolution", resolution);
  78387. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  78388. };
  78389. // Compose
  78390. 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);
  78391. 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);
  78392. this.lensFlareComposePostProcess.onApply = function (effect) {
  78393. if (!_this._scene.activeCamera) {
  78394. return;
  78395. }
  78396. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78397. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  78398. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  78399. // Lens start rotation matrix
  78400. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  78401. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  78402. 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));
  78403. camRot *= 4.0;
  78404. 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);
  78405. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  78406. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  78407. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  78408. };
  78409. };
  78410. // Create depth-of-field post-process
  78411. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  78412. var _this = this;
  78413. 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);
  78414. this.depthOfFieldPostProcess.onApply = function (effect) {
  78415. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  78416. effect.setTexture("depthSampler", _this._getDepthTexture());
  78417. effect.setFloat("distance", _this.depthOfFieldDistance);
  78418. };
  78419. // Add to pipeline
  78420. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  78421. };
  78422. // Create motion blur post-process
  78423. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  78424. var _this = this;
  78425. 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);
  78426. var motionScale = 0;
  78427. var prevViewProjection = BABYLON.Matrix.Identity();
  78428. var invViewProjection = BABYLON.Matrix.Identity();
  78429. var viewProjection = BABYLON.Matrix.Identity();
  78430. var screenSize = BABYLON.Vector2.Zero();
  78431. this.motionBlurPostProcess.onApply = function (effect) {
  78432. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  78433. viewProjection.invertToRef(invViewProjection);
  78434. effect.setMatrix("inverseViewProjection", invViewProjection);
  78435. effect.setMatrix("prevViewProjection", prevViewProjection);
  78436. prevViewProjection = viewProjection;
  78437. screenSize.x = _this.motionBlurPostProcess.width;
  78438. screenSize.y = _this.motionBlurPostProcess.height;
  78439. effect.setVector2("screenSize", screenSize);
  78440. motionScale = scene.getEngine().getFps() / 60.0;
  78441. effect.setFloat("motionScale", motionScale);
  78442. effect.setFloat("motionStrength", _this.motionStrength);
  78443. effect.setTexture("depthSampler", _this._getDepthTexture());
  78444. };
  78445. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  78446. };
  78447. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  78448. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  78449. var renderer = this._scene.enableGeometryBufferRenderer();
  78450. return renderer.getGBuffer().textures[0];
  78451. }
  78452. return this._scene.enableDepthRenderer().getDepthMap();
  78453. };
  78454. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  78455. for (var i = 0; i < this._cameras.length; i++) {
  78456. var camera = this._cameras[i];
  78457. if (this.originalPostProcess) {
  78458. this.originalPostProcess.dispose(camera);
  78459. }
  78460. if (this.downSampleX4PostProcess) {
  78461. this.downSampleX4PostProcess.dispose(camera);
  78462. }
  78463. if (this.brightPassPostProcess) {
  78464. this.brightPassPostProcess.dispose(camera);
  78465. }
  78466. if (this.textureAdderPostProcess) {
  78467. this.textureAdderPostProcess.dispose(camera);
  78468. }
  78469. if (this.textureAdderFinalPostProcess) {
  78470. this.textureAdderFinalPostProcess.dispose(camera);
  78471. }
  78472. if (this.volumetricLightPostProcess) {
  78473. this.volumetricLightPostProcess.dispose(camera);
  78474. }
  78475. if (this.volumetricLightSmoothXPostProcess) {
  78476. this.volumetricLightSmoothXPostProcess.dispose(camera);
  78477. }
  78478. if (this.volumetricLightSmoothYPostProcess) {
  78479. this.volumetricLightSmoothYPostProcess.dispose(camera);
  78480. }
  78481. if (this.volumetricLightMergePostProces) {
  78482. this.volumetricLightMergePostProces.dispose(camera);
  78483. }
  78484. if (this.volumetricLightFinalPostProcess) {
  78485. this.volumetricLightFinalPostProcess.dispose(camera);
  78486. }
  78487. if (this.lensFlarePostProcess) {
  78488. this.lensFlarePostProcess.dispose(camera);
  78489. }
  78490. if (this.lensFlareComposePostProcess) {
  78491. this.lensFlareComposePostProcess.dispose(camera);
  78492. }
  78493. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  78494. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  78495. }
  78496. if (this.luminancePostProcess) {
  78497. this.luminancePostProcess.dispose(camera);
  78498. }
  78499. if (this.hdrPostProcess) {
  78500. this.hdrPostProcess.dispose(camera);
  78501. }
  78502. if (this.hdrFinalPostProcess) {
  78503. this.hdrFinalPostProcess.dispose(camera);
  78504. }
  78505. if (this.depthOfFieldPostProcess) {
  78506. this.depthOfFieldPostProcess.dispose(camera);
  78507. }
  78508. if (this.motionBlurPostProcess) {
  78509. this.motionBlurPostProcess.dispose(camera);
  78510. }
  78511. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  78512. this.blurHPostProcesses[j].dispose(camera);
  78513. }
  78514. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  78515. this.blurVPostProcesses[j].dispose(camera);
  78516. }
  78517. }
  78518. this.originalPostProcess = null;
  78519. this.downSampleX4PostProcess = null;
  78520. this.brightPassPostProcess = null;
  78521. this.textureAdderPostProcess = null;
  78522. this.textureAdderFinalPostProcess = null;
  78523. this.volumetricLightPostProcess = null;
  78524. this.volumetricLightSmoothXPostProcess = null;
  78525. this.volumetricLightSmoothYPostProcess = null;
  78526. this.volumetricLightMergePostProces = null;
  78527. this.volumetricLightFinalPostProcess = null;
  78528. this.lensFlarePostProcess = null;
  78529. this.lensFlareComposePostProcess = null;
  78530. this.luminancePostProcess = null;
  78531. this.hdrPostProcess = null;
  78532. this.hdrFinalPostProcess = null;
  78533. this.depthOfFieldPostProcess = null;
  78534. this.motionBlurPostProcess = null;
  78535. this.luminanceDownSamplePostProcesses = [];
  78536. this.blurHPostProcesses = [];
  78537. this.blurVPostProcesses = [];
  78538. };
  78539. /**
  78540. * Dispose of the pipeline and stop all post processes
  78541. */
  78542. StandardRenderingPipeline.prototype.dispose = function () {
  78543. this._disposePostProcesses();
  78544. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78545. _super.prototype.dispose.call(this);
  78546. };
  78547. /**
  78548. * Serialize the rendering pipeline (Used when exporting)
  78549. * @returns the serialized object
  78550. */
  78551. StandardRenderingPipeline.prototype.serialize = function () {
  78552. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78553. if (this.sourceLight) {
  78554. serializationObject.sourceLightId = this.sourceLight.id;
  78555. }
  78556. serializationObject.customType = "StandardRenderingPipeline";
  78557. return serializationObject;
  78558. };
  78559. /**
  78560. * Parse the serialized pipeline
  78561. * @param source Source pipeline.
  78562. * @param scene The scene to load the pipeline to.
  78563. * @param rootUrl The URL of the serialized pipeline.
  78564. * @returns An instantiated pipeline from the serialized object.
  78565. */
  78566. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78567. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78568. if (source.sourceLightId) {
  78569. p.sourceLight = scene.getLightByID(source.sourceLightId);
  78570. }
  78571. return p;
  78572. };
  78573. // Luminance steps
  78574. StandardRenderingPipeline.LuminanceSteps = 6;
  78575. __decorate([
  78576. BABYLON.serialize()
  78577. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  78578. __decorate([
  78579. BABYLON.serialize()
  78580. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  78581. __decorate([
  78582. BABYLON.serialize()
  78583. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  78584. __decorate([
  78585. BABYLON.serialize()
  78586. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  78587. __decorate([
  78588. BABYLON.serializeAsTexture("lensTexture")
  78589. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  78590. __decorate([
  78591. BABYLON.serialize()
  78592. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  78593. __decorate([
  78594. BABYLON.serialize()
  78595. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  78596. __decorate([
  78597. BABYLON.serialize()
  78598. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  78599. __decorate([
  78600. BABYLON.serialize()
  78601. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  78602. __decorate([
  78603. BABYLON.serialize()
  78604. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  78605. __decorate([
  78606. BABYLON.serialize()
  78607. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  78608. __decorate([
  78609. BABYLON.serializeAsTexture("lensColorTexture")
  78610. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  78611. __decorate([
  78612. BABYLON.serialize()
  78613. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  78614. __decorate([
  78615. BABYLON.serialize()
  78616. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  78617. __decorate([
  78618. BABYLON.serialize()
  78619. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  78620. __decorate([
  78621. BABYLON.serialize()
  78622. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  78623. __decorate([
  78624. BABYLON.serializeAsTexture("lensStarTexture")
  78625. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  78626. __decorate([
  78627. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  78628. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  78629. __decorate([
  78630. BABYLON.serialize()
  78631. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  78632. __decorate([
  78633. BABYLON.serialize()
  78634. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  78635. __decorate([
  78636. BABYLON.serialize()
  78637. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  78638. __decorate([
  78639. BABYLON.serialize()
  78640. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  78641. __decorate([
  78642. BABYLON.serialize()
  78643. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  78644. __decorate([
  78645. BABYLON.serialize()
  78646. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  78647. __decorate([
  78648. BABYLON.serialize()
  78649. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  78650. __decorate([
  78651. BABYLON.serialize()
  78652. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  78653. __decorate([
  78654. BABYLON.serialize()
  78655. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  78656. __decorate([
  78657. BABYLON.serialize()
  78658. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  78659. __decorate([
  78660. BABYLON.serialize()
  78661. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  78662. __decorate([
  78663. BABYLON.serialize()
  78664. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  78665. return StandardRenderingPipeline;
  78666. }(BABYLON.PostProcessRenderPipeline));
  78667. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  78668. })(BABYLON || (BABYLON = {}));
  78669. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  78670. var BABYLON;
  78671. (function (BABYLON) {
  78672. var FxaaPostProcess = /** @class */ (function (_super) {
  78673. __extends(FxaaPostProcess, _super);
  78674. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78675. if (camera === void 0) { camera = null; }
  78676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78677. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  78678. var defines = _this._getDefines();
  78679. _this.updateEffect(defines);
  78680. _this.onApplyObservable.add(function (effect) {
  78681. var texelSize = _this.texelSize;
  78682. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  78683. });
  78684. return _this;
  78685. }
  78686. FxaaPostProcess.prototype._getDefines = function () {
  78687. var engine = this.getEngine();
  78688. if (!engine) {
  78689. return null;
  78690. }
  78691. var glInfo = engine.getGlInfo();
  78692. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  78693. return "#define MALI 1\n";
  78694. }
  78695. return null;
  78696. };
  78697. return FxaaPostProcess;
  78698. }(BABYLON.PostProcess));
  78699. BABYLON.FxaaPostProcess = FxaaPostProcess;
  78700. })(BABYLON || (BABYLON = {}));
  78701. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  78702. var BABYLON;
  78703. (function (BABYLON) {
  78704. /**
  78705. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  78706. */
  78707. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  78708. __extends(ChromaticAberrationPostProcess, _super);
  78709. /**
  78710. * Creates a new instance ChromaticAberrationPostProcess
  78711. * @param name The name of the effect.
  78712. * @param screenWidth The width of the screen to apply the effect on.
  78713. * @param screenHeight The height of the screen to apply the effect on.
  78714. * @param options The required width/height ratio to downsize to before computing the render pass.
  78715. * @param camera The camera to apply the render pass to.
  78716. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78717. * @param engine The engine which the post process will be applied. (default: current engine)
  78718. * @param reusable If the post process can be reused on the same frame. (default: false)
  78719. * @param textureType Type of textures used when performing the post process. (default: 0)
  78720. * @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)
  78721. */
  78722. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78724. if (blockCompilation === void 0) { blockCompilation = false; }
  78725. 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;
  78726. /**
  78727. * The amount of seperation of rgb channels (default: 30)
  78728. */
  78729. _this.aberrationAmount = 30;
  78730. /**
  78731. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  78732. */
  78733. _this.radialIntensity = 0;
  78734. /**
  78735. * 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))
  78736. */
  78737. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  78738. /**
  78739. * 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))
  78740. */
  78741. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  78742. _this.onApplyObservable.add(function (effect) {
  78743. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  78744. effect.setFloat('screen_width', screenWidth);
  78745. effect.setFloat('screen_height', screenHeight);
  78746. effect.setFloat('radialIntensity', _this.radialIntensity);
  78747. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  78748. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  78749. });
  78750. return _this;
  78751. }
  78752. return ChromaticAberrationPostProcess;
  78753. }(BABYLON.PostProcess));
  78754. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  78755. })(BABYLON || (BABYLON = {}));
  78756. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  78757. var BABYLON;
  78758. (function (BABYLON) {
  78759. /**
  78760. * The GrainPostProcess adds noise to the image at mid luminance levels
  78761. */
  78762. var GrainPostProcess = /** @class */ (function (_super) {
  78763. __extends(GrainPostProcess, _super);
  78764. /**
  78765. * Creates a new instance of @see GrainPostProcess
  78766. * @param name The name of the effect.
  78767. * @param options The required width/height ratio to downsize to before computing the render pass.
  78768. * @param camera The camera to apply the render pass to.
  78769. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78770. * @param engine The engine which the post process will be applied. (default: current engine)
  78771. * @param reusable If the post process can be reused on the same frame. (default: false)
  78772. * @param textureType Type of textures used when performing the post process. (default: 0)
  78773. * @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)
  78774. */
  78775. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78777. if (blockCompilation === void 0) { blockCompilation = false; }
  78778. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78779. /**
  78780. * The intensity of the grain added (default: 30)
  78781. */
  78782. _this.intensity = 30;
  78783. /**
  78784. * If the grain should be randomized on every frame
  78785. */
  78786. _this.animated = false;
  78787. _this.onApplyObservable.add(function (effect) {
  78788. effect.setFloat('intensity', _this.intensity);
  78789. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  78790. });
  78791. return _this;
  78792. }
  78793. return GrainPostProcess;
  78794. }(BABYLON.PostProcess));
  78795. BABYLON.GrainPostProcess = GrainPostProcess;
  78796. })(BABYLON || (BABYLON = {}));
  78797. //# sourceMappingURL=babylon.grainPostProcess.js.map
  78798. var BABYLON;
  78799. (function (BABYLON) {
  78800. /**
  78801. * The SharpenPostProcess applies a sharpen kernel to every pixel
  78802. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78803. */
  78804. var SharpenPostProcess = /** @class */ (function (_super) {
  78805. __extends(SharpenPostProcess, _super);
  78806. /**
  78807. * Creates a new instance ConvolutionPostProcess
  78808. * @param name The name of the effect.
  78809. * @param options The required width/height ratio to downsize to before computing the render pass.
  78810. * @param camera The camera to apply the render pass to.
  78811. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78812. * @param engine The engine which the post process will be applied. (default: current engine)
  78813. * @param reusable If the post process can be reused on the same frame. (default: false)
  78814. * @param textureType Type of textures used when performing the post process. (default: 0)
  78815. * @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)
  78816. */
  78817. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78818. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78819. if (blockCompilation === void 0) { blockCompilation = false; }
  78820. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78821. /**
  78822. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  78823. */
  78824. _this.colorAmount = 1.0;
  78825. /**
  78826. * How much sharpness should be applied (default: 0.3)
  78827. */
  78828. _this.edgeAmount = 0.3;
  78829. _this.onApply = function (effect) {
  78830. effect.setFloat2("screenSize", _this.width, _this.height);
  78831. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  78832. };
  78833. return _this;
  78834. }
  78835. return SharpenPostProcess;
  78836. }(BABYLON.PostProcess));
  78837. BABYLON.SharpenPostProcess = SharpenPostProcess;
  78838. })(BABYLON || (BABYLON = {}));
  78839. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  78840. var BABYLON;
  78841. (function (BABYLON) {
  78842. /**
  78843. * The Blur Post Process which blurs an image based on a kernel and direction.
  78844. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  78845. */
  78846. var BlurPostProcess = /** @class */ (function (_super) {
  78847. __extends(BlurPostProcess, _super);
  78848. /**
  78849. * Creates a new instance BlurPostProcess
  78850. * @param name The name of the effect.
  78851. * @param direction The direction in which to blur the image.
  78852. * @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.
  78853. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  78854. * @param camera The camera to apply the render pass to.
  78855. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78856. * @param engine The engine which the post process will be applied. (default: current engine)
  78857. * @param reusable If the post process can be reused on the same frame. (default: false)
  78858. * @param textureType Type of textures used when performing the post process. (default: 0)
  78859. * @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)
  78860. */
  78861. function BlurPostProcess(name,
  78862. /** The direction in which to blur the image. */
  78863. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  78864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78865. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78866. if (defines === void 0) { defines = ""; }
  78867. if (blockCompilation === void 0) { blockCompilation = false; }
  78868. 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;
  78869. _this.direction = direction;
  78870. _this.blockCompilation = blockCompilation;
  78871. _this._packedFloat = false;
  78872. _this._staticDefines = "";
  78873. _this._staticDefines = defines;
  78874. _this.onApplyObservable.add(function (effect) {
  78875. if (_this._outputTexture) {
  78876. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  78877. }
  78878. else {
  78879. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  78880. }
  78881. });
  78882. _this.kernel = kernel;
  78883. return _this;
  78884. }
  78885. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  78886. /**
  78887. * Gets the length in pixels of the blur sample region
  78888. */
  78889. get: function () {
  78890. return this._idealKernel;
  78891. },
  78892. /**
  78893. * Sets the length in pixels of the blur sample region
  78894. */
  78895. set: function (v) {
  78896. if (this._idealKernel === v) {
  78897. return;
  78898. }
  78899. v = Math.max(v, 1);
  78900. this._idealKernel = v;
  78901. this._kernel = this._nearestBestKernel(v);
  78902. if (!this.blockCompilation) {
  78903. this._updateParameters();
  78904. }
  78905. },
  78906. enumerable: true,
  78907. configurable: true
  78908. });
  78909. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  78910. /**
  78911. * Gets wether or not the blur is unpacking/repacking floats
  78912. */
  78913. get: function () {
  78914. return this._packedFloat;
  78915. },
  78916. /**
  78917. * Sets wether or not the blur needs to unpack/repack floats
  78918. */
  78919. set: function (v) {
  78920. if (this._packedFloat === v) {
  78921. return;
  78922. }
  78923. this._packedFloat = v;
  78924. if (!this.blockCompilation) {
  78925. this._updateParameters();
  78926. }
  78927. },
  78928. enumerable: true,
  78929. configurable: true
  78930. });
  78931. /**
  78932. * Updates the effect with the current post process compile time values and recompiles the shader.
  78933. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78934. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78935. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78936. * @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
  78937. * @param onCompiled Called when the shader has been compiled.
  78938. * @param onError Called if there is an error when compiling a shader.
  78939. */
  78940. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78941. if (defines === void 0) { defines = null; }
  78942. if (uniforms === void 0) { uniforms = null; }
  78943. if (samplers === void 0) { samplers = null; }
  78944. this._updateParameters(onCompiled, onError);
  78945. };
  78946. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  78947. // Generate sampling offsets and weights
  78948. var N = this._kernel;
  78949. var centerIndex = (N - 1) / 2;
  78950. // Generate Gaussian sampling weights over kernel
  78951. var offsets = [];
  78952. var weights = [];
  78953. var totalWeight = 0;
  78954. for (var i = 0; i < N; i++) {
  78955. var u = i / (N - 1);
  78956. var w = this._gaussianWeight(u * 2.0 - 1);
  78957. offsets[i] = (i - centerIndex);
  78958. weights[i] = w;
  78959. totalWeight += w;
  78960. }
  78961. // Normalize weights
  78962. for (var i = 0; i < weights.length; i++) {
  78963. weights[i] /= totalWeight;
  78964. }
  78965. // Optimize: combine samples to take advantage of hardware linear sampling
  78966. // Walk from left to center, combining pairs (symmetrically)
  78967. var linearSamplingWeights = [];
  78968. var linearSamplingOffsets = [];
  78969. var linearSamplingMap = [];
  78970. for (var i = 0; i <= centerIndex; i += 2) {
  78971. var j = Math.min(i + 1, Math.floor(centerIndex));
  78972. var singleCenterSample = i === j;
  78973. if (singleCenterSample) {
  78974. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78975. }
  78976. else {
  78977. var sharedCell = j === centerIndex;
  78978. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  78979. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  78980. if (offsetLinear === 0) {
  78981. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78982. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  78983. }
  78984. else {
  78985. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  78986. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  78987. }
  78988. }
  78989. }
  78990. for (var i = 0; i < linearSamplingMap.length; i++) {
  78991. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  78992. linearSamplingWeights[i] = linearSamplingMap[i].w;
  78993. }
  78994. // Replace with optimized
  78995. offsets = linearSamplingOffsets;
  78996. weights = linearSamplingWeights;
  78997. // Generate shaders
  78998. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  78999. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  79000. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  79001. var defines = "";
  79002. defines += this._staticDefines;
  79003. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  79004. if (this._staticDefines.indexOf("DOF") != -1) {
  79005. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  79006. varyingCount--;
  79007. }
  79008. for (var i = 0; i < varyingCount; i++) {
  79009. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  79010. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  79011. }
  79012. var depCount = 0;
  79013. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  79014. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  79015. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  79016. depCount++;
  79017. }
  79018. if (this.packedFloat) {
  79019. defines += "#define PACKEDFLOAT 1";
  79020. }
  79021. this.blockCompilation = false;
  79022. _super.prototype.updateEffect.call(this, defines, null, null, {
  79023. varyingCount: varyingCount,
  79024. depCount: depCount
  79025. }, onCompiled, onError);
  79026. };
  79027. /**
  79028. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  79029. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  79030. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  79031. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  79032. * The gaps between physical kernels are compensated for in the weighting of the samples
  79033. * @param idealKernel Ideal blur kernel.
  79034. * @return Nearest best kernel.
  79035. */
  79036. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  79037. var v = Math.round(idealKernel);
  79038. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  79039. var k = _a[_i];
  79040. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  79041. return Math.max(k, 3);
  79042. }
  79043. }
  79044. return Math.max(v, 3);
  79045. };
  79046. /**
  79047. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  79048. * @param x The point on the Gaussian distribution to sample.
  79049. * @return the value of the Gaussian function at x.
  79050. */
  79051. BlurPostProcess.prototype._gaussianWeight = function (x) {
  79052. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  79053. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  79054. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  79055. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  79056. // truncated at around 1.3% of peak strength.
  79057. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  79058. var sigma = (1 / 3);
  79059. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  79060. var exponent = -((x * x) / (2.0 * sigma * sigma));
  79061. var weight = (1.0 / denominator) * Math.exp(exponent);
  79062. return weight;
  79063. };
  79064. /**
  79065. * Generates a string that can be used as a floating point number in GLSL.
  79066. * @param x Value to print.
  79067. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  79068. * @return GLSL float string.
  79069. */
  79070. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  79071. if (decimalFigures === void 0) { decimalFigures = 8; }
  79072. return x.toFixed(decimalFigures).replace(/0+$/, '');
  79073. };
  79074. return BlurPostProcess;
  79075. }(BABYLON.PostProcess));
  79076. BABYLON.BlurPostProcess = BlurPostProcess;
  79077. })(BABYLON || (BABYLON = {}));
  79078. //# sourceMappingURL=babylon.blurPostProcess.js.map
  79079. var BABYLON;
  79080. (function (BABYLON) {
  79081. /**
  79082. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  79083. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  79084. * based on samples that have a large difference in distance than the center pixel.
  79085. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79086. */
  79087. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  79088. __extends(DepthOfFieldBlurPostProcess, _super);
  79089. /**
  79090. * Creates a new instance CircleOfConfusionPostProcess
  79091. * @param name The name of the effect.
  79092. * @param scene The scene the effect belongs to.
  79093. * @param direction The direction the blur should be applied.
  79094. * @param kernel The size of the kernel used to blur.
  79095. * @param options The required width/height ratio to downsize to before computing the render pass.
  79096. * @param camera The camera to apply the render pass to.
  79097. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  79098. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  79099. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79100. * @param engine The engine which the post process will be applied. (default: current engine)
  79101. * @param reusable If the post process can be reused on the same frame. (default: false)
  79102. * @param textureType Type of textures used when performing the post process. (default: 0)
  79103. * @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)
  79104. */
  79105. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  79106. if (imageToBlur === void 0) { imageToBlur = null; }
  79107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79108. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79109. if (blockCompilation === void 0) { blockCompilation = false; }
  79110. 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;
  79111. _this.direction = direction;
  79112. _this.onApplyObservable.add(function (effect) {
  79113. if (imageToBlur != null) {
  79114. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  79115. }
  79116. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79117. if (scene.activeCamera) {
  79118. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  79119. }
  79120. });
  79121. return _this;
  79122. }
  79123. return DepthOfFieldBlurPostProcess;
  79124. }(BABYLON.BlurPostProcess));
  79125. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  79126. })(BABYLON || (BABYLON = {}));
  79127. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  79128. var BABYLON;
  79129. (function (BABYLON) {
  79130. /**
  79131. * Options to be set when merging outputs from the default pipeline.
  79132. */
  79133. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  79134. function DepthOfFieldMergePostProcessOptions() {
  79135. }
  79136. return DepthOfFieldMergePostProcessOptions;
  79137. }());
  79138. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  79139. /**
  79140. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79141. */
  79142. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  79143. __extends(DepthOfFieldMergePostProcess, _super);
  79144. /**
  79145. * Creates a new instance of DepthOfFieldMergePostProcess
  79146. * @param name The name of the effect.
  79147. * @param originalFromInput Post process which's input will be used for the merge.
  79148. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  79149. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  79150. * @param options The required width/height ratio to downsize to before computing the render pass.
  79151. * @param camera The camera to apply the render pass to.
  79152. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79153. * @param engine The engine which the post process will be applied. (default: current engine)
  79154. * @param reusable If the post process can be reused on the same frame. (default: false)
  79155. * @param textureType Type of textures used when performing the post process. (default: 0)
  79156. * @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)
  79157. */
  79158. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79159. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79160. if (blockCompilation === void 0) { blockCompilation = false; }
  79161. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79162. _this.blurSteps = blurSteps;
  79163. _this.onApplyObservable.add(function (effect) {
  79164. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79165. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  79166. blurSteps.forEach(function (step, index) {
  79167. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  79168. });
  79169. });
  79170. if (!blockCompilation) {
  79171. _this.updateEffect();
  79172. }
  79173. return _this;
  79174. }
  79175. /**
  79176. * Updates the effect with the current post process compile time values and recompiles the shader.
  79177. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  79178. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  79179. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  79180. * @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
  79181. * @param onCompiled Called when the shader has been compiled.
  79182. * @param onError Called if there is an error when compiling a shader.
  79183. */
  79184. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  79185. if (defines === void 0) { defines = null; }
  79186. if (uniforms === void 0) { uniforms = null; }
  79187. if (samplers === void 0) { samplers = null; }
  79188. if (!defines) {
  79189. defines = "";
  79190. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  79191. }
  79192. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  79193. };
  79194. return DepthOfFieldMergePostProcess;
  79195. }(BABYLON.PostProcess));
  79196. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  79197. })(BABYLON || (BABYLON = {}));
  79198. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  79199. var BABYLON;
  79200. (function (BABYLON) {
  79201. /**
  79202. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  79203. */
  79204. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  79205. __extends(CircleOfConfusionPostProcess, _super);
  79206. /**
  79207. * Creates a new instance CircleOfConfusionPostProcess
  79208. * @param name The name of the effect.
  79209. * @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.
  79210. * @param options The required width/height ratio to downsize to before computing the render pass.
  79211. * @param camera The camera to apply the render pass to.
  79212. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79213. * @param engine The engine which the post process will be applied. (default: current engine)
  79214. * @param reusable If the post process can be reused on the same frame. (default: false)
  79215. * @param textureType Type of textures used when performing the post process. (default: 0)
  79216. * @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)
  79217. */
  79218. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79219. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79220. if (blockCompilation === void 0) { blockCompilation = false; }
  79221. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79222. /**
  79223. * 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.
  79224. */
  79225. _this.lensSize = 50;
  79226. /**
  79227. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79228. */
  79229. _this.fStop = 1.4;
  79230. /**
  79231. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79232. */
  79233. _this.focusDistance = 2000;
  79234. /**
  79235. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  79236. */
  79237. _this.focalLength = 50;
  79238. _this._depthTexture = null;
  79239. _this._depthTexture = depthTexture;
  79240. _this.onApplyObservable.add(function (effect) {
  79241. if (!_this._depthTexture) {
  79242. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  79243. return;
  79244. }
  79245. effect.setTexture("depthSampler", _this._depthTexture);
  79246. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  79247. var aperture = _this.lensSize / _this.fStop;
  79248. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  79249. effect.setFloat('focusDistance', _this.focusDistance);
  79250. effect.setFloat('cocPrecalculation', cocPrecalculation);
  79251. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  79252. });
  79253. return _this;
  79254. }
  79255. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  79256. /**
  79257. * 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.
  79258. */
  79259. set: function (value) {
  79260. this._depthTexture = value;
  79261. },
  79262. enumerable: true,
  79263. configurable: true
  79264. });
  79265. return CircleOfConfusionPostProcess;
  79266. }(BABYLON.PostProcess));
  79267. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  79268. })(BABYLON || (BABYLON = {}));
  79269. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  79270. var BABYLON;
  79271. (function (BABYLON) {
  79272. /**
  79273. * Specifies the level of max blur that should be applied when using the depth of field effect
  79274. */
  79275. var DepthOfFieldEffectBlurLevel;
  79276. (function (DepthOfFieldEffectBlurLevel) {
  79277. /**
  79278. * Subtle blur
  79279. */
  79280. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  79281. /**
  79282. * Medium blur
  79283. */
  79284. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  79285. /**
  79286. * Large blur
  79287. */
  79288. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  79289. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  79290. ;
  79291. /**
  79292. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  79293. */
  79294. var DepthOfFieldEffect = /** @class */ (function (_super) {
  79295. __extends(DepthOfFieldEffect, _super);
  79296. /**
  79297. * Creates a new instance DepthOfFieldEffect
  79298. * @param scene The scene the effect belongs to.
  79299. * @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.
  79300. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79301. * @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)
  79302. */
  79303. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  79304. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  79305. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79306. if (blockCompilation === void 0) { blockCompilation = false; }
  79307. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  79308. return _this._effects;
  79309. }, true) || this;
  79310. /**
  79311. * @hidden Internal post processes in depth of field effect
  79312. */
  79313. _this._effects = [];
  79314. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  79315. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79316. // 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)
  79317. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  79318. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  79319. _this._depthOfFieldBlurY = [];
  79320. _this._depthOfFieldBlurX = [];
  79321. var blurCount = 1;
  79322. var kernelSize = 15;
  79323. switch (blurLevel) {
  79324. case DepthOfFieldEffectBlurLevel.High: {
  79325. blurCount = 3;
  79326. kernelSize = 51;
  79327. break;
  79328. }
  79329. case DepthOfFieldEffectBlurLevel.Medium: {
  79330. blurCount = 2;
  79331. kernelSize = 31;
  79332. break;
  79333. }
  79334. default: {
  79335. kernelSize = 15;
  79336. blurCount = 1;
  79337. break;
  79338. }
  79339. }
  79340. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  79341. var ratio = 1.0;
  79342. for (var i = 0; i < blurCount; i++) {
  79343. 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);
  79344. blurY.autoClear = false;
  79345. ratio = 0.75 / Math.pow(2, i);
  79346. 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);
  79347. blurX.autoClear = false;
  79348. _this._depthOfFieldBlurY.push(blurY);
  79349. _this._depthOfFieldBlurX.push(blurX);
  79350. }
  79351. // Set all post processes on the effect.
  79352. _this._effects = [_this._circleOfConfusion];
  79353. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  79354. _this._effects.push(_this._depthOfFieldBlurY[i]);
  79355. _this._effects.push(_this._depthOfFieldBlurX[i]);
  79356. }
  79357. // Merge blurred images with original image based on circleOfConfusion
  79358. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79359. _this._dofMerge.autoClear = false;
  79360. _this._effects.push(_this._dofMerge);
  79361. return _this;
  79362. }
  79363. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  79364. get: function () {
  79365. return this._circleOfConfusion.focalLength;
  79366. },
  79367. /**
  79368. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  79369. */
  79370. set: function (value) {
  79371. this._circleOfConfusion.focalLength = value;
  79372. },
  79373. enumerable: true,
  79374. configurable: true
  79375. });
  79376. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  79377. get: function () {
  79378. return this._circleOfConfusion.fStop;
  79379. },
  79380. /**
  79381. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  79382. */
  79383. set: function (value) {
  79384. this._circleOfConfusion.fStop = value;
  79385. },
  79386. enumerable: true,
  79387. configurable: true
  79388. });
  79389. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  79390. get: function () {
  79391. return this._circleOfConfusion.focusDistance;
  79392. },
  79393. /**
  79394. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  79395. */
  79396. set: function (value) {
  79397. this._circleOfConfusion.focusDistance = value;
  79398. },
  79399. enumerable: true,
  79400. configurable: true
  79401. });
  79402. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  79403. get: function () {
  79404. return this._circleOfConfusion.lensSize;
  79405. },
  79406. /**
  79407. * 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.
  79408. */
  79409. set: function (value) {
  79410. this._circleOfConfusion.lensSize = value;
  79411. },
  79412. enumerable: true,
  79413. configurable: true
  79414. });
  79415. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  79416. /**
  79417. * 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.
  79418. */
  79419. set: function (value) {
  79420. this._circleOfConfusion.depthTexture = value;
  79421. },
  79422. enumerable: true,
  79423. configurable: true
  79424. });
  79425. /**
  79426. * Disposes each of the internal effects for a given camera.
  79427. * @param camera The camera to dispose the effect on.
  79428. */
  79429. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  79430. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79431. this._effects[effectIndex].dispose(camera);
  79432. }
  79433. };
  79434. /**
  79435. * @hidden Internal
  79436. */
  79437. DepthOfFieldEffect.prototype._updateEffects = function () {
  79438. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79439. this._effects[effectIndex].updateEffect();
  79440. }
  79441. };
  79442. /**
  79443. * Internal
  79444. * @returns if all the contained post processes are ready.
  79445. * @hidden
  79446. */
  79447. DepthOfFieldEffect.prototype._isReady = function () {
  79448. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79449. if (!this._effects[effectIndex].isReady()) {
  79450. return false;
  79451. }
  79452. }
  79453. return true;
  79454. };
  79455. return DepthOfFieldEffect;
  79456. }(BABYLON.PostProcessRenderEffect));
  79457. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  79458. })(BABYLON || (BABYLON = {}));
  79459. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  79460. var BABYLON;
  79461. (function (BABYLON) {
  79462. /**
  79463. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  79464. */
  79465. var BloomMergePostProcess = /** @class */ (function (_super) {
  79466. __extends(BloomMergePostProcess, _super);
  79467. /**
  79468. * Creates a new instance of @see BloomMergePostProcess
  79469. * @param name The name of the effect.
  79470. * @param originalFromInput Post process which's input will be used for the merge.
  79471. * @param blurred Blurred highlights post process which's output will be used.
  79472. * @param weight Weight of the bloom to be added to the original input.
  79473. * @param options The required width/height ratio to downsize to before computing the render pass.
  79474. * @param camera The camera to apply the render pass to.
  79475. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79476. * @param engine The engine which the post process will be applied. (default: current engine)
  79477. * @param reusable If the post process can be reused on the same frame. (default: false)
  79478. * @param textureType Type of textures used when performing the post process. (default: 0)
  79479. * @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)
  79480. */
  79481. function BloomMergePostProcess(name, originalFromInput, blurred,
  79482. /** Weight of the bloom to be added to the original input. */
  79483. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79484. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79485. if (blockCompilation === void 0) { blockCompilation = false; }
  79486. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  79487. _this.weight = weight;
  79488. _this.onApplyObservable.add(function (effect) {
  79489. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  79490. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  79491. effect.setFloat("bloomWeight", _this.weight);
  79492. });
  79493. if (!blockCompilation) {
  79494. _this.updateEffect();
  79495. }
  79496. return _this;
  79497. }
  79498. return BloomMergePostProcess;
  79499. }(BABYLON.PostProcess));
  79500. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  79501. })(BABYLON || (BABYLON = {}));
  79502. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  79503. var BABYLON;
  79504. (function (BABYLON) {
  79505. /**
  79506. * 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.
  79507. */
  79508. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  79509. __extends(ExtractHighlightsPostProcess, _super);
  79510. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79511. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79512. if (blockCompilation === void 0) { blockCompilation = false; }
  79513. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  79514. /**
  79515. * The luminance threshold, pixels below this value will be set to black.
  79516. */
  79517. _this.threshold = 0.9;
  79518. /** @hidden */
  79519. _this._exposure = 1;
  79520. /**
  79521. * Post process which has the input texture to be used when performing highlight extraction
  79522. * @hidden
  79523. */
  79524. _this._inputPostProcess = null;
  79525. _this.onApplyObservable.add(function (effect) {
  79526. if (_this._inputPostProcess) {
  79527. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  79528. }
  79529. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  79530. effect.setFloat('exposure', _this._exposure);
  79531. });
  79532. return _this;
  79533. }
  79534. return ExtractHighlightsPostProcess;
  79535. }(BABYLON.PostProcess));
  79536. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  79537. })(BABYLON || (BABYLON = {}));
  79538. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  79539. var BABYLON;
  79540. (function (BABYLON) {
  79541. /**
  79542. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  79543. */
  79544. var BloomEffect = /** @class */ (function (_super) {
  79545. __extends(BloomEffect, _super);
  79546. /**
  79547. * Creates a new instance of @see BloomEffect
  79548. * @param scene The scene the effect belongs to.
  79549. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  79550. * @param bloomKernel The size of the kernel to be used when applying the blur.
  79551. * @param bloomWeight The the strength of bloom.
  79552. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  79553. * @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)
  79554. */
  79555. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  79556. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  79557. if (blockCompilation === void 0) { blockCompilation = false; }
  79558. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  79559. return _this._effects;
  79560. }, true) || this;
  79561. _this.bloomScale = bloomScale;
  79562. /**
  79563. * @hidden Internal
  79564. */
  79565. _this._effects = [];
  79566. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79567. _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);
  79568. _this._blurX.alwaysForcePOT = true;
  79569. _this._blurX.autoClear = false;
  79570. _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);
  79571. _this._blurY.alwaysForcePOT = true;
  79572. _this._blurY.autoClear = false;
  79573. _this.kernel = bloomKernel;
  79574. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  79575. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  79576. _this._merge.autoClear = false;
  79577. _this._effects.push(_this._merge);
  79578. return _this;
  79579. }
  79580. Object.defineProperty(BloomEffect.prototype, "threshold", {
  79581. /**
  79582. * The luminance threshold to find bright areas of the image to bloom.
  79583. */
  79584. get: function () {
  79585. return this._downscale.threshold;
  79586. },
  79587. set: function (value) {
  79588. this._downscale.threshold = value;
  79589. },
  79590. enumerable: true,
  79591. configurable: true
  79592. });
  79593. Object.defineProperty(BloomEffect.prototype, "weight", {
  79594. /**
  79595. * The strength of the bloom.
  79596. */
  79597. get: function () {
  79598. return this._merge.weight;
  79599. },
  79600. set: function (value) {
  79601. this._merge.weight = value;
  79602. },
  79603. enumerable: true,
  79604. configurable: true
  79605. });
  79606. Object.defineProperty(BloomEffect.prototype, "kernel", {
  79607. /**
  79608. * Specifies the size of the bloom blur kernel, relative to the final output size
  79609. */
  79610. get: function () {
  79611. return this._blurX.kernel / this.bloomScale;
  79612. },
  79613. set: function (value) {
  79614. this._blurX.kernel = value * this.bloomScale;
  79615. this._blurY.kernel = value * this.bloomScale;
  79616. },
  79617. enumerable: true,
  79618. configurable: true
  79619. });
  79620. /**
  79621. * Disposes each of the internal effects for a given camera.
  79622. * @param camera The camera to dispose the effect on.
  79623. */
  79624. BloomEffect.prototype.disposeEffects = function (camera) {
  79625. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79626. this._effects[effectIndex].dispose(camera);
  79627. }
  79628. };
  79629. /**
  79630. * @hidden Internal
  79631. */
  79632. BloomEffect.prototype._updateEffects = function () {
  79633. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79634. this._effects[effectIndex].updateEffect();
  79635. }
  79636. };
  79637. /**
  79638. * Internal
  79639. * @returns if all the contained post processes are ready.
  79640. * @hidden
  79641. */
  79642. BloomEffect.prototype._isReady = function () {
  79643. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  79644. if (!this._effects[effectIndex].isReady()) {
  79645. return false;
  79646. }
  79647. }
  79648. return true;
  79649. };
  79650. return BloomEffect;
  79651. }(BABYLON.PostProcessRenderEffect));
  79652. BABYLON.BloomEffect = BloomEffect;
  79653. })(BABYLON || (BABYLON = {}));
  79654. //# sourceMappingURL=babylon.bloomEffect.js.map
  79655. var BABYLON;
  79656. (function (BABYLON) {
  79657. /**
  79658. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  79659. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  79660. */
  79661. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  79662. __extends(DefaultRenderingPipeline, _super);
  79663. /**
  79664. * @constructor
  79665. * @param {string} name - The rendering pipeline name (default: "")
  79666. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  79667. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  79668. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  79669. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  79670. */
  79671. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  79672. if (name === void 0) { name = ""; }
  79673. if (hdr === void 0) { hdr = true; }
  79674. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  79675. if (automaticBuild === void 0) { automaticBuild = true; }
  79676. var _this = _super.call(this, scene.getEngine(), name) || this;
  79677. _this._camerasToBeAttached = [];
  79678. /**
  79679. * ID of the sharpen post process,
  79680. */
  79681. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  79682. /**
  79683. * ID of the image processing post process;
  79684. */
  79685. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  79686. /**
  79687. * ID of the Fast Approximate Anti-Aliasing post process;
  79688. */
  79689. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  79690. /**
  79691. * ID of the chromatic aberration post process,
  79692. */
  79693. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  79694. /**
  79695. * ID of the grain post process
  79696. */
  79697. _this.GrainPostProcessId = "GrainPostProcessEffect";
  79698. /**
  79699. * Glow post process which adds a glow to emmisive areas of the image
  79700. */
  79701. _this._glowLayer = null;
  79702. /**
  79703. * Animations which can be used to tweak settings over a period of time
  79704. */
  79705. _this.animations = [];
  79706. _this._imageProcessingConfigurationObserver = null;
  79707. // Values
  79708. _this._sharpenEnabled = false;
  79709. _this._bloomEnabled = false;
  79710. _this._depthOfFieldEnabled = false;
  79711. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  79712. _this._fxaaEnabled = false;
  79713. _this._imageProcessingEnabled = true;
  79714. _this._bloomScale = 0.5;
  79715. _this._chromaticAberrationEnabled = false;
  79716. _this._grainEnabled = false;
  79717. _this._buildAllowed = true;
  79718. _this._resizeObserver = null;
  79719. _this._hardwareScaleLevel = 1.0;
  79720. _this._bloomKernel = 64;
  79721. /**
  79722. * Specifies the weight of the bloom in the final rendering
  79723. */
  79724. _this._bloomWeight = 0.15;
  79725. /**
  79726. * Specifies the luma threshold for the area that will be blurred by the bloom
  79727. */
  79728. _this._bloomThreshold = 0.9;
  79729. _this._samples = 1;
  79730. _this._hasCleared = false;
  79731. _this._prevPostProcess = null;
  79732. _this._prevPrevPostProcess = null;
  79733. _this._cameras = cameras || scene.cameras;
  79734. _this._cameras = _this._cameras.slice();
  79735. _this._camerasToBeAttached = _this._cameras.slice();
  79736. _this._buildAllowed = automaticBuild;
  79737. // Initialize
  79738. _this._scene = scene;
  79739. var caps = _this._scene.getEngine().getCaps();
  79740. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  79741. // Misc
  79742. if (_this._hdr) {
  79743. if (caps.textureHalfFloatRender) {
  79744. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79745. }
  79746. else if (caps.textureFloatRender) {
  79747. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79748. }
  79749. }
  79750. else {
  79751. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79752. }
  79753. // Attach
  79754. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79755. var engine = _this._scene.getEngine();
  79756. // Create post processes before hand so they can be modified before enabled.
  79757. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  79758. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79759. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  79760. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  79761. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  79762. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79763. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  79764. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  79765. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  79766. _this._resizeObserver = engine.onResizeObservable.add(function () {
  79767. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  79768. _this.bloomKernel = _this.bloomKernel;
  79769. });
  79770. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  79771. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  79772. });
  79773. _this._buildPipeline();
  79774. return _this;
  79775. }
  79776. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  79777. get: function () {
  79778. return this._sharpenEnabled;
  79779. },
  79780. /**
  79781. * Enable or disable the sharpen process from the pipeline
  79782. */
  79783. set: function (enabled) {
  79784. if (this._sharpenEnabled === enabled) {
  79785. return;
  79786. }
  79787. this._sharpenEnabled = enabled;
  79788. this._buildPipeline();
  79789. },
  79790. enumerable: true,
  79791. configurable: true
  79792. });
  79793. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  79794. /**
  79795. * Specifies the size of the bloom blur kernel, relative to the final output size
  79796. */
  79797. get: function () {
  79798. return this._bloomKernel;
  79799. },
  79800. set: function (value) {
  79801. this._bloomKernel = value;
  79802. this.bloom.kernel = value / this._hardwareScaleLevel;
  79803. },
  79804. enumerable: true,
  79805. configurable: true
  79806. });
  79807. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  79808. get: function () {
  79809. return this._bloomWeight;
  79810. },
  79811. /**
  79812. * The strength of the bloom.
  79813. */
  79814. set: function (value) {
  79815. if (this._bloomWeight === value) {
  79816. return;
  79817. }
  79818. this.bloom.weight = value;
  79819. this._bloomWeight = value;
  79820. },
  79821. enumerable: true,
  79822. configurable: true
  79823. });
  79824. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  79825. get: function () {
  79826. return this._bloomThreshold;
  79827. },
  79828. /**
  79829. * The strength of the bloom.
  79830. */
  79831. set: function (value) {
  79832. if (this._bloomThreshold === value) {
  79833. return;
  79834. }
  79835. this.bloom.threshold = value;
  79836. this._bloomThreshold = value;
  79837. },
  79838. enumerable: true,
  79839. configurable: true
  79840. });
  79841. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  79842. get: function () {
  79843. return this._bloomScale;
  79844. },
  79845. /**
  79846. * The scale of the bloom, lower value will provide better performance.
  79847. */
  79848. set: function (value) {
  79849. if (this._bloomScale === value) {
  79850. return;
  79851. }
  79852. this._bloomScale = value;
  79853. // recreate bloom and dispose old as this setting is not dynamic
  79854. this._rebuildBloom();
  79855. this._buildPipeline();
  79856. },
  79857. enumerable: true,
  79858. configurable: true
  79859. });
  79860. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  79861. get: function () {
  79862. return this._bloomEnabled;
  79863. },
  79864. /**
  79865. * Enable or disable the bloom from the pipeline
  79866. */
  79867. set: function (enabled) {
  79868. if (this._bloomEnabled === enabled) {
  79869. return;
  79870. }
  79871. this._bloomEnabled = enabled;
  79872. this._buildPipeline();
  79873. },
  79874. enumerable: true,
  79875. configurable: true
  79876. });
  79877. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  79878. // recreate bloom and dispose old as this setting is not dynamic
  79879. var oldBloom = this.bloom;
  79880. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  79881. this.bloom.threshold = oldBloom.threshold;
  79882. for (var i = 0; i < this._cameras.length; i++) {
  79883. oldBloom.disposeEffects(this._cameras[i]);
  79884. }
  79885. };
  79886. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  79887. /**
  79888. * If the depth of field is enabled.
  79889. */
  79890. get: function () {
  79891. return this._depthOfFieldEnabled;
  79892. },
  79893. set: function (enabled) {
  79894. if (this._depthOfFieldEnabled === enabled) {
  79895. return;
  79896. }
  79897. this._depthOfFieldEnabled = enabled;
  79898. this._buildPipeline();
  79899. },
  79900. enumerable: true,
  79901. configurable: true
  79902. });
  79903. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  79904. /**
  79905. * Blur level of the depth of field effect. (Higher blur will effect performance)
  79906. */
  79907. get: function () {
  79908. return this._depthOfFieldBlurLevel;
  79909. },
  79910. set: function (value) {
  79911. if (this._depthOfFieldBlurLevel === value) {
  79912. return;
  79913. }
  79914. this._depthOfFieldBlurLevel = value;
  79915. // recreate dof and dispose old as this setting is not dynamic
  79916. var oldDof = this.depthOfField;
  79917. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  79918. this.depthOfField.focalLength = oldDof.focalLength;
  79919. this.depthOfField.focusDistance = oldDof.focusDistance;
  79920. this.depthOfField.fStop = oldDof.fStop;
  79921. this.depthOfField.lensSize = oldDof.lensSize;
  79922. for (var i = 0; i < this._cameras.length; i++) {
  79923. oldDof.disposeEffects(this._cameras[i]);
  79924. }
  79925. this._buildPipeline();
  79926. },
  79927. enumerable: true,
  79928. configurable: true
  79929. });
  79930. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  79931. get: function () {
  79932. return this._fxaaEnabled;
  79933. },
  79934. /**
  79935. * If the anti aliasing is enabled.
  79936. */
  79937. set: function (enabled) {
  79938. if (this._fxaaEnabled === enabled) {
  79939. return;
  79940. }
  79941. this._fxaaEnabled = enabled;
  79942. this._buildPipeline();
  79943. },
  79944. enumerable: true,
  79945. configurable: true
  79946. });
  79947. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  79948. get: function () {
  79949. return this._samples;
  79950. },
  79951. /**
  79952. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79953. */
  79954. set: function (sampleCount) {
  79955. if (this._samples === sampleCount) {
  79956. return;
  79957. }
  79958. this._samples = sampleCount;
  79959. this._buildPipeline();
  79960. },
  79961. enumerable: true,
  79962. configurable: true
  79963. });
  79964. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  79965. get: function () {
  79966. return this._imageProcessingEnabled;
  79967. },
  79968. /**
  79969. * If image processing is enabled.
  79970. */
  79971. set: function (enabled) {
  79972. if (this._imageProcessingEnabled === enabled) {
  79973. return;
  79974. }
  79975. this._imageProcessingEnabled = enabled;
  79976. this._buildPipeline();
  79977. },
  79978. enumerable: true,
  79979. configurable: true
  79980. });
  79981. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  79982. get: function () {
  79983. return this._glowLayer == null;
  79984. },
  79985. /**
  79986. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  79987. */
  79988. set: function (enabled) {
  79989. if (enabled && !this._glowLayer) {
  79990. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  79991. }
  79992. else if (!enabled && this._glowLayer) {
  79993. this._glowLayer.dispose();
  79994. this._glowLayer = null;
  79995. }
  79996. },
  79997. enumerable: true,
  79998. configurable: true
  79999. });
  80000. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  80001. get: function () {
  80002. return this._chromaticAberrationEnabled;
  80003. },
  80004. /**
  80005. * Enable or disable the chromaticAberration process from the pipeline
  80006. */
  80007. set: function (enabled) {
  80008. if (this._chromaticAberrationEnabled === enabled) {
  80009. return;
  80010. }
  80011. this._chromaticAberrationEnabled = enabled;
  80012. this._buildPipeline();
  80013. },
  80014. enumerable: true,
  80015. configurable: true
  80016. });
  80017. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  80018. get: function () {
  80019. return this._grainEnabled;
  80020. },
  80021. /**
  80022. * Enable or disable the grain process from the pipeline
  80023. */
  80024. set: function (enabled) {
  80025. if (this._grainEnabled === enabled) {
  80026. return;
  80027. }
  80028. this._grainEnabled = enabled;
  80029. this._buildPipeline();
  80030. },
  80031. enumerable: true,
  80032. configurable: true
  80033. });
  80034. /**
  80035. * Force the compilation of the entire pipeline.
  80036. */
  80037. DefaultRenderingPipeline.prototype.prepare = function () {
  80038. var previousState = this._buildAllowed;
  80039. this._buildAllowed = true;
  80040. this._buildPipeline();
  80041. this._buildAllowed = previousState;
  80042. };
  80043. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  80044. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  80045. if (this._hasCleared) {
  80046. postProcess.autoClear = false;
  80047. }
  80048. else {
  80049. postProcess.autoClear = true;
  80050. this._scene.autoClear = false;
  80051. this._hasCleared = true;
  80052. }
  80053. if (!skipTextureSharing) {
  80054. if (this._prevPrevPostProcess) {
  80055. postProcess.shareOutputWith(this._prevPrevPostProcess);
  80056. }
  80057. else {
  80058. postProcess.useOwnOutput();
  80059. }
  80060. if (this._prevPostProcess) {
  80061. this._prevPrevPostProcess = this._prevPostProcess;
  80062. }
  80063. this._prevPostProcess = postProcess;
  80064. }
  80065. };
  80066. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  80067. var _this = this;
  80068. if (!this._buildAllowed) {
  80069. return;
  80070. }
  80071. this._scene.autoClear = true;
  80072. var engine = this._scene.getEngine();
  80073. this._disposePostProcesses();
  80074. if (this._cameras !== null) {
  80075. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80076. // get back cameras to be used to reattach pipeline
  80077. this._cameras = this._camerasToBeAttached.slice();
  80078. }
  80079. this._reset();
  80080. this._prevPostProcess = null;
  80081. this._prevPrevPostProcess = null;
  80082. this._hasCleared = false;
  80083. if (this.depthOfFieldEnabled) {
  80084. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  80085. this.depthOfField.depthTexture = depthTexture;
  80086. if (!this.depthOfField._isReady()) {
  80087. this.depthOfField._updateEffects();
  80088. }
  80089. this.addEffect(this.depthOfField);
  80090. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  80091. }
  80092. if (this.bloomEnabled) {
  80093. if (!this.bloom._isReady()) {
  80094. this.bloom._updateEffects();
  80095. }
  80096. this.addEffect(this.bloom);
  80097. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  80098. }
  80099. if (this._imageProcessingEnabled) {
  80100. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80101. if (this._hdr) {
  80102. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  80103. this._setAutoClearAndTextureSharing(this.imageProcessing);
  80104. }
  80105. else {
  80106. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  80107. }
  80108. }
  80109. if (this.sharpenEnabled) {
  80110. if (!this.sharpen.isReady()) {
  80111. this.sharpen.updateEffect();
  80112. }
  80113. this.addEffect(this._sharpenEffect);
  80114. this._setAutoClearAndTextureSharing(this.sharpen);
  80115. }
  80116. if (this.grainEnabled) {
  80117. if (!this.grain.isReady()) {
  80118. this.grain.updateEffect();
  80119. }
  80120. this.addEffect(this._grainEffect);
  80121. this._setAutoClearAndTextureSharing(this.grain);
  80122. }
  80123. if (this.chromaticAberrationEnabled) {
  80124. if (!this.chromaticAberration.isReady()) {
  80125. this.chromaticAberration.updateEffect();
  80126. }
  80127. this.addEffect(this._chromaticAberrationEffect);
  80128. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  80129. }
  80130. if (this.fxaaEnabled) {
  80131. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  80132. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  80133. this._setAutoClearAndTextureSharing(this.fxaa, true);
  80134. }
  80135. if (this._cameras !== null) {
  80136. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  80137. }
  80138. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  80139. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  80140. }
  80141. };
  80142. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  80143. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  80144. for (var i = 0; i < this._cameras.length; i++) {
  80145. var camera = this._cameras[i];
  80146. if (this.imageProcessing) {
  80147. this.imageProcessing.dispose(camera);
  80148. }
  80149. if (this.fxaa) {
  80150. this.fxaa.dispose(camera);
  80151. }
  80152. // These are created in the constructor and should not be disposed on every pipeline change
  80153. if (disposeNonRecreated) {
  80154. if (this.sharpen) {
  80155. this.sharpen.dispose(camera);
  80156. }
  80157. if (this.depthOfField) {
  80158. this.depthOfField.disposeEffects(camera);
  80159. }
  80160. if (this.bloom) {
  80161. this.bloom.disposeEffects(camera);
  80162. }
  80163. if (this.chromaticAberration) {
  80164. this.chromaticAberration.dispose(camera);
  80165. }
  80166. if (this.grain) {
  80167. this.grain.dispose(camera);
  80168. }
  80169. if (this._glowLayer) {
  80170. this._glowLayer.dispose();
  80171. }
  80172. }
  80173. }
  80174. this.imageProcessing = null;
  80175. this.fxaa = null;
  80176. if (disposeNonRecreated) {
  80177. this.sharpen = null;
  80178. this._sharpenEffect = null;
  80179. this.depthOfField = null;
  80180. this.bloom = null;
  80181. this.chromaticAberration = null;
  80182. this._chromaticAberrationEffect = null;
  80183. this.grain = null;
  80184. this._grainEffect = null;
  80185. this._glowLayer = null;
  80186. }
  80187. };
  80188. /**
  80189. * Adds a camera to the pipeline
  80190. * @param camera the camera to be added
  80191. */
  80192. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  80193. this._camerasToBeAttached.push(camera);
  80194. this._buildPipeline();
  80195. };
  80196. /**
  80197. * Removes a camera from the pipeline
  80198. * @param camera the camera to remove
  80199. */
  80200. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  80201. var index = this._camerasToBeAttached.indexOf(camera);
  80202. this._camerasToBeAttached.splice(index, 1);
  80203. this._buildPipeline();
  80204. };
  80205. /**
  80206. * Dispose of the pipeline and stop all post processes
  80207. */
  80208. DefaultRenderingPipeline.prototype.dispose = function () {
  80209. this._disposePostProcesses(true);
  80210. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  80211. this._scene.autoClear = true;
  80212. if (this._resizeObserver) {
  80213. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  80214. this._resizeObserver = null;
  80215. }
  80216. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  80217. _super.prototype.dispose.call(this);
  80218. };
  80219. /**
  80220. * Serialize the rendering pipeline (Used when exporting)
  80221. * @returns the serialized object
  80222. */
  80223. DefaultRenderingPipeline.prototype.serialize = function () {
  80224. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80225. serializationObject.customType = "DefaultRenderingPipeline";
  80226. return serializationObject;
  80227. };
  80228. /**
  80229. * Parse the serialized pipeline
  80230. * @param source Source pipeline.
  80231. * @param scene The scene to load the pipeline to.
  80232. * @param rootUrl The URL of the serialized pipeline.
  80233. * @returns An instantiated pipeline from the serialized object.
  80234. */
  80235. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  80236. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  80237. };
  80238. __decorate([
  80239. BABYLON.serialize()
  80240. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  80241. __decorate([
  80242. BABYLON.serialize()
  80243. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  80244. __decorate([
  80245. BABYLON.serialize()
  80246. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  80247. __decorate([
  80248. BABYLON.serialize()
  80249. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  80250. __decorate([
  80251. BABYLON.serialize()
  80252. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  80253. __decorate([
  80254. BABYLON.serialize()
  80255. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  80256. __decorate([
  80257. BABYLON.serialize()
  80258. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  80259. __decorate([
  80260. BABYLON.serialize()
  80261. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  80262. __decorate([
  80263. BABYLON.serialize()
  80264. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  80265. __decorate([
  80266. BABYLON.serialize()
  80267. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  80268. __decorate([
  80269. BABYLON.serialize()
  80270. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  80271. __decorate([
  80272. BABYLON.serialize()
  80273. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  80274. __decorate([
  80275. BABYLON.serialize()
  80276. ], DefaultRenderingPipeline.prototype, "samples", null);
  80277. __decorate([
  80278. BABYLON.serialize()
  80279. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  80280. __decorate([
  80281. BABYLON.serialize()
  80282. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  80283. __decorate([
  80284. BABYLON.serialize()
  80285. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  80286. __decorate([
  80287. BABYLON.serialize()
  80288. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  80289. return DefaultRenderingPipeline;
  80290. }(BABYLON.PostProcessRenderPipeline));
  80291. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  80292. })(BABYLON || (BABYLON = {}));
  80293. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  80294. var BABYLON;
  80295. (function (BABYLON) {
  80296. /**
  80297. * @hidden
  80298. */
  80299. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  80300. __extends(ImageProcessingConfigurationDefines, _super);
  80301. function ImageProcessingConfigurationDefines() {
  80302. var _this = _super.call(this) || this;
  80303. _this.IMAGEPROCESSING = false;
  80304. _this.VIGNETTE = false;
  80305. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80306. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80307. _this.TONEMAPPING = false;
  80308. _this.TONEMAPPING_ACES = false;
  80309. _this.CONTRAST = false;
  80310. _this.COLORCURVES = false;
  80311. _this.COLORGRADING = false;
  80312. _this.COLORGRADING3D = false;
  80313. _this.SAMPLER3DGREENDEPTH = false;
  80314. _this.SAMPLER3DBGRMAP = false;
  80315. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80316. _this.EXPOSURE = false;
  80317. _this.rebuild();
  80318. return _this;
  80319. }
  80320. return ImageProcessingConfigurationDefines;
  80321. }(BABYLON.MaterialDefines));
  80322. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  80323. /**
  80324. * This groups together the common properties used for image processing either in direct forward pass
  80325. * or through post processing effect depending on the use of the image processing pipeline in your scene
  80326. * or not.
  80327. */
  80328. var ImageProcessingConfiguration = /** @class */ (function () {
  80329. function ImageProcessingConfiguration() {
  80330. /**
  80331. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  80332. */
  80333. this.colorCurves = new BABYLON.ColorCurves();
  80334. this._colorCurvesEnabled = false;
  80335. this._colorGradingEnabled = false;
  80336. this._colorGradingWithGreenDepth = true;
  80337. this._colorGradingBGR = true;
  80338. /** @hidden */
  80339. this._exposure = 1.0;
  80340. this._toneMappingEnabled = false;
  80341. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  80342. this._contrast = 1.0;
  80343. /**
  80344. * Vignette stretch size.
  80345. */
  80346. this.vignetteStretch = 0;
  80347. /**
  80348. * Vignette centre X Offset.
  80349. */
  80350. this.vignetteCentreX = 0;
  80351. /**
  80352. * Vignette centre Y Offset.
  80353. */
  80354. this.vignetteCentreY = 0;
  80355. /**
  80356. * Vignette weight or intensity of the vignette effect.
  80357. */
  80358. this.vignetteWeight = 1.5;
  80359. /**
  80360. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80361. * if vignetteEnabled is set to true.
  80362. */
  80363. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80364. /**
  80365. * Camera field of view used by the Vignette effect.
  80366. */
  80367. this.vignetteCameraFov = 0.5;
  80368. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  80369. this._vignetteEnabled = false;
  80370. this._applyByPostProcess = false;
  80371. this._isEnabled = true;
  80372. /**
  80373. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  80374. */
  80375. this.onUpdateParameters = new BABYLON.Observable();
  80376. }
  80377. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  80378. /**
  80379. * Gets wether the color curves effect is enabled.
  80380. */
  80381. get: function () {
  80382. return this._colorCurvesEnabled;
  80383. },
  80384. /**
  80385. * Sets wether the color curves effect is enabled.
  80386. */
  80387. set: function (value) {
  80388. if (this._colorCurvesEnabled === value) {
  80389. return;
  80390. }
  80391. this._colorCurvesEnabled = value;
  80392. this._updateParameters();
  80393. },
  80394. enumerable: true,
  80395. configurable: true
  80396. });
  80397. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  80398. /**
  80399. * Gets wether the color grading effect is enabled.
  80400. */
  80401. get: function () {
  80402. return this._colorGradingEnabled;
  80403. },
  80404. /**
  80405. * Sets wether the color grading effect is enabled.
  80406. */
  80407. set: function (value) {
  80408. if (this._colorGradingEnabled === value) {
  80409. return;
  80410. }
  80411. this._colorGradingEnabled = value;
  80412. this._updateParameters();
  80413. },
  80414. enumerable: true,
  80415. configurable: true
  80416. });
  80417. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  80418. /**
  80419. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  80420. */
  80421. get: function () {
  80422. return this._colorGradingWithGreenDepth;
  80423. },
  80424. /**
  80425. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  80426. */
  80427. set: function (value) {
  80428. if (this._colorGradingWithGreenDepth === value) {
  80429. return;
  80430. }
  80431. this._colorGradingWithGreenDepth = value;
  80432. this._updateParameters();
  80433. },
  80434. enumerable: true,
  80435. configurable: true
  80436. });
  80437. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  80438. /**
  80439. * Gets wether the color grading texture contains BGR values.
  80440. */
  80441. get: function () {
  80442. return this._colorGradingBGR;
  80443. },
  80444. /**
  80445. * Sets wether the color grading texture contains BGR values.
  80446. */
  80447. set: function (value) {
  80448. if (this._colorGradingBGR === value) {
  80449. return;
  80450. }
  80451. this._colorGradingBGR = value;
  80452. this._updateParameters();
  80453. },
  80454. enumerable: true,
  80455. configurable: true
  80456. });
  80457. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  80458. /**
  80459. * Gets the Exposure used in the effect.
  80460. */
  80461. get: function () {
  80462. return this._exposure;
  80463. },
  80464. /**
  80465. * Sets the Exposure used in the effect.
  80466. */
  80467. set: function (value) {
  80468. if (this._exposure === value) {
  80469. return;
  80470. }
  80471. this._exposure = value;
  80472. this._updateParameters();
  80473. },
  80474. enumerable: true,
  80475. configurable: true
  80476. });
  80477. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  80478. /**
  80479. * Gets wether the tone mapping effect is enabled.
  80480. */
  80481. get: function () {
  80482. return this._toneMappingEnabled;
  80483. },
  80484. /**
  80485. * Sets wether the tone mapping effect is enabled.
  80486. */
  80487. set: function (value) {
  80488. if (this._toneMappingEnabled === value) {
  80489. return;
  80490. }
  80491. this._toneMappingEnabled = value;
  80492. this._updateParameters();
  80493. },
  80494. enumerable: true,
  80495. configurable: true
  80496. });
  80497. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  80498. /**
  80499. * Gets the type of tone mapping effect.
  80500. */
  80501. get: function () {
  80502. return this._toneMappingType;
  80503. },
  80504. /**
  80505. * Sets the type of tone mapping effect used in BabylonJS.
  80506. */
  80507. set: function (value) {
  80508. if (this._toneMappingType === value) {
  80509. return;
  80510. }
  80511. this._toneMappingType = value;
  80512. this._updateParameters();
  80513. },
  80514. enumerable: true,
  80515. configurable: true
  80516. });
  80517. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  80518. /**
  80519. * Gets the contrast used in the effect.
  80520. */
  80521. get: function () {
  80522. return this._contrast;
  80523. },
  80524. /**
  80525. * Sets the contrast used in the effect.
  80526. */
  80527. set: function (value) {
  80528. if (this._contrast === value) {
  80529. return;
  80530. }
  80531. this._contrast = value;
  80532. this._updateParameters();
  80533. },
  80534. enumerable: true,
  80535. configurable: true
  80536. });
  80537. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  80538. /**
  80539. * Gets the vignette blend mode allowing different kind of effect.
  80540. */
  80541. get: function () {
  80542. return this._vignetteBlendMode;
  80543. },
  80544. /**
  80545. * Sets the vignette blend mode allowing different kind of effect.
  80546. */
  80547. set: function (value) {
  80548. if (this._vignetteBlendMode === value) {
  80549. return;
  80550. }
  80551. this._vignetteBlendMode = value;
  80552. this._updateParameters();
  80553. },
  80554. enumerable: true,
  80555. configurable: true
  80556. });
  80557. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  80558. /**
  80559. * Gets wether the vignette effect is enabled.
  80560. */
  80561. get: function () {
  80562. return this._vignetteEnabled;
  80563. },
  80564. /**
  80565. * Sets wether the vignette effect is enabled.
  80566. */
  80567. set: function (value) {
  80568. if (this._vignetteEnabled === value) {
  80569. return;
  80570. }
  80571. this._vignetteEnabled = value;
  80572. this._updateParameters();
  80573. },
  80574. enumerable: true,
  80575. configurable: true
  80576. });
  80577. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  80578. /**
  80579. * Gets wether the image processing is applied through a post process or not.
  80580. */
  80581. get: function () {
  80582. return this._applyByPostProcess;
  80583. },
  80584. /**
  80585. * Sets wether the image processing is applied through a post process or not.
  80586. */
  80587. set: function (value) {
  80588. if (this._applyByPostProcess === value) {
  80589. return;
  80590. }
  80591. this._applyByPostProcess = value;
  80592. this._updateParameters();
  80593. },
  80594. enumerable: true,
  80595. configurable: true
  80596. });
  80597. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  80598. /**
  80599. * Gets wether the image processing is enabled or not.
  80600. */
  80601. get: function () {
  80602. return this._isEnabled;
  80603. },
  80604. /**
  80605. * Sets wether the image processing is enabled or not.
  80606. */
  80607. set: function (value) {
  80608. if (this._isEnabled === value) {
  80609. return;
  80610. }
  80611. this._isEnabled = value;
  80612. this._updateParameters();
  80613. },
  80614. enumerable: true,
  80615. configurable: true
  80616. });
  80617. /**
  80618. * Method called each time the image processing information changes requires to recompile the effect.
  80619. */
  80620. ImageProcessingConfiguration.prototype._updateParameters = function () {
  80621. this.onUpdateParameters.notifyObservers(this);
  80622. };
  80623. ImageProcessingConfiguration.prototype.getClassName = function () {
  80624. return "ImageProcessingConfiguration";
  80625. };
  80626. /**
  80627. * Prepare the list of uniforms associated with the Image Processing effects.
  80628. * @param uniformsList The list of uniforms used in the effect
  80629. * @param defines the list of defines currently in use
  80630. */
  80631. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  80632. if (defines.EXPOSURE) {
  80633. uniforms.push("exposureLinear");
  80634. }
  80635. if (defines.CONTRAST) {
  80636. uniforms.push("contrast");
  80637. }
  80638. if (defines.COLORGRADING) {
  80639. uniforms.push("colorTransformSettings");
  80640. }
  80641. if (defines.VIGNETTE) {
  80642. uniforms.push("vInverseScreenSize");
  80643. uniforms.push("vignetteSettings1");
  80644. uniforms.push("vignetteSettings2");
  80645. }
  80646. if (defines.COLORCURVES) {
  80647. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  80648. }
  80649. };
  80650. /**
  80651. * Prepare the list of samplers associated with the Image Processing effects.
  80652. * @param uniformsList The list of uniforms used in the effect
  80653. * @param defines the list of defines currently in use
  80654. */
  80655. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  80656. if (defines.COLORGRADING) {
  80657. samplersList.push("txColorTransform");
  80658. }
  80659. };
  80660. /**
  80661. * Prepare the list of defines associated to the shader.
  80662. * @param defines the list of defines to complete
  80663. */
  80664. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  80665. if (forPostProcess === void 0) { forPostProcess = false; }
  80666. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  80667. defines.VIGNETTE = false;
  80668. defines.TONEMAPPING = false;
  80669. defines.TONEMAPPING_ACES = false;
  80670. defines.CONTRAST = false;
  80671. defines.EXPOSURE = false;
  80672. defines.COLORCURVES = false;
  80673. defines.COLORGRADING = false;
  80674. defines.COLORGRADING3D = false;
  80675. defines.IMAGEPROCESSING = false;
  80676. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  80677. return;
  80678. }
  80679. defines.VIGNETTE = this.vignetteEnabled;
  80680. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  80681. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  80682. defines.TONEMAPPING = this.toneMappingEnabled;
  80683. switch (this._toneMappingType) {
  80684. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  80685. defines.TONEMAPPING_ACES = true;
  80686. break;
  80687. }
  80688. defines.CONTRAST = (this.contrast !== 1.0);
  80689. defines.EXPOSURE = (this.exposure !== 1.0);
  80690. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  80691. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  80692. if (defines.COLORGRADING) {
  80693. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  80694. }
  80695. else {
  80696. defines.COLORGRADING3D = false;
  80697. }
  80698. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  80699. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  80700. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  80701. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  80702. };
  80703. /**
  80704. * Returns true if all the image processing information are ready.
  80705. */
  80706. ImageProcessingConfiguration.prototype.isReady = function () {
  80707. // Color Grading texure can not be none blocking.
  80708. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  80709. };
  80710. /**
  80711. * Binds the image processing to the shader.
  80712. * @param effect The effect to bind to
  80713. */
  80714. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  80715. if (aspectRatio === void 0) { aspectRatio = 1; }
  80716. // Color Curves
  80717. if (this._colorCurvesEnabled && this.colorCurves) {
  80718. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  80719. }
  80720. // Vignette
  80721. if (this._vignetteEnabled) {
  80722. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  80723. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  80724. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  80725. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  80726. var vignetteScaleX = vignetteScaleY * aspectRatio;
  80727. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  80728. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  80729. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  80730. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  80731. var vignettePower = -2.0 * this.vignetteWeight;
  80732. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  80733. }
  80734. // Exposure
  80735. effect.setFloat("exposureLinear", this.exposure);
  80736. // Contrast
  80737. effect.setFloat("contrast", this.contrast);
  80738. // Color transform settings
  80739. if (this.colorGradingTexture) {
  80740. effect.setTexture("txColorTransform", this.colorGradingTexture);
  80741. var textureSize = this.colorGradingTexture.getSize().height;
  80742. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  80743. 0.5 / textureSize, // textureOffset
  80744. textureSize, // textureSize
  80745. this.colorGradingTexture.level // weight
  80746. );
  80747. }
  80748. };
  80749. /**
  80750. * Clones the current image processing instance.
  80751. * @return The cloned image processing
  80752. */
  80753. ImageProcessingConfiguration.prototype.clone = function () {
  80754. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  80755. };
  80756. /**
  80757. * Serializes the current image processing instance to a json representation.
  80758. * @return a JSON representation
  80759. */
  80760. ImageProcessingConfiguration.prototype.serialize = function () {
  80761. return BABYLON.SerializationHelper.Serialize(this);
  80762. };
  80763. /**
  80764. * Parses the image processing from a json representation.
  80765. * @param source the JSON source to parse
  80766. * @return The parsed image processing
  80767. */
  80768. ImageProcessingConfiguration.Parse = function (source) {
  80769. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  80770. };
  80771. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  80772. /**
  80773. * Used to apply the vignette as a mix with the pixel color.
  80774. */
  80775. get: function () {
  80776. return this._VIGNETTEMODE_MULTIPLY;
  80777. },
  80778. enumerable: true,
  80779. configurable: true
  80780. });
  80781. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  80782. /**
  80783. * Used to apply the vignette as a replacement of the pixel color.
  80784. */
  80785. get: function () {
  80786. return this._VIGNETTEMODE_OPAQUE;
  80787. },
  80788. enumerable: true,
  80789. configurable: true
  80790. });
  80791. /**
  80792. * Default tone mapping applied in BabylonJS.
  80793. */
  80794. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  80795. /**
  80796. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  80797. * to other engines rendering to increase portability.
  80798. */
  80799. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  80800. // Static constants associated to the image processing.
  80801. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  80802. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  80803. __decorate([
  80804. BABYLON.serializeAsColorCurves()
  80805. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  80806. __decorate([
  80807. BABYLON.serialize()
  80808. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  80809. __decorate([
  80810. BABYLON.serializeAsTexture()
  80811. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  80812. __decorate([
  80813. BABYLON.serialize()
  80814. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  80815. __decorate([
  80816. BABYLON.serialize()
  80817. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  80818. __decorate([
  80819. BABYLON.serialize()
  80820. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  80821. __decorate([
  80822. BABYLON.serialize()
  80823. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  80824. __decorate([
  80825. BABYLON.serialize()
  80826. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  80827. __decorate([
  80828. BABYLON.serialize()
  80829. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  80830. __decorate([
  80831. BABYLON.serialize()
  80832. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  80833. __decorate([
  80834. BABYLON.serialize()
  80835. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  80836. __decorate([
  80837. BABYLON.serialize()
  80838. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  80839. __decorate([
  80840. BABYLON.serialize()
  80841. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  80842. __decorate([
  80843. BABYLON.serialize()
  80844. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  80845. __decorate([
  80846. BABYLON.serializeAsColor4()
  80847. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  80848. __decorate([
  80849. BABYLON.serialize()
  80850. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  80851. __decorate([
  80852. BABYLON.serialize()
  80853. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  80854. __decorate([
  80855. BABYLON.serialize()
  80856. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  80857. __decorate([
  80858. BABYLON.serialize()
  80859. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  80860. __decorate([
  80861. BABYLON.serialize()
  80862. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  80863. return ImageProcessingConfiguration;
  80864. }());
  80865. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  80866. })(BABYLON || (BABYLON = {}));
  80867. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  80868. var BABYLON;
  80869. (function (BABYLON) {
  80870. /**
  80871. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  80872. * It can help converting any input color in a desired output one. This can then be used to create effects
  80873. * from sepia, black and white to sixties or futuristic rendering...
  80874. *
  80875. * The only supported format is currently 3dl.
  80876. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  80877. */
  80878. var ColorGradingTexture = /** @class */ (function (_super) {
  80879. __extends(ColorGradingTexture, _super);
  80880. /**
  80881. * Instantiates a ColorGradingTexture from the following parameters.
  80882. *
  80883. * @param url The location of the color gradind data (currently only supporting 3dl)
  80884. * @param scene The scene the texture will be used in
  80885. */
  80886. function ColorGradingTexture(url, scene) {
  80887. var _this = _super.call(this, scene) || this;
  80888. if (!url) {
  80889. return _this;
  80890. }
  80891. _this._engine = scene.getEngine();
  80892. _this._textureMatrix = BABYLON.Matrix.Identity();
  80893. _this.name = url;
  80894. _this.url = url;
  80895. _this.hasAlpha = false;
  80896. _this.isCube = false;
  80897. _this.is3D = _this._engine.webGLVersion > 1;
  80898. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80899. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80900. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80901. _this.anisotropicFilteringLevel = 1;
  80902. _this._texture = _this._getFromCache(url, true);
  80903. if (!_this._texture) {
  80904. if (!scene.useDelayedTextureLoading) {
  80905. _this.loadTexture();
  80906. }
  80907. else {
  80908. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80909. }
  80910. }
  80911. return _this;
  80912. }
  80913. /**
  80914. * Returns the texture matrix used in most of the material.
  80915. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  80916. */
  80917. ColorGradingTexture.prototype.getTextureMatrix = function () {
  80918. return this._textureMatrix;
  80919. };
  80920. /**
  80921. * Occurs when the file being loaded is a .3dl LUT file.
  80922. */
  80923. ColorGradingTexture.prototype.load3dlTexture = function () {
  80924. var engine = this._engine;
  80925. var texture;
  80926. if (engine.webGLVersion === 1) {
  80927. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80928. }
  80929. else {
  80930. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80931. }
  80932. this._texture = texture;
  80933. var callback = function (text) {
  80934. if (typeof text !== "string") {
  80935. return;
  80936. }
  80937. var data = null;
  80938. var tempData = null;
  80939. var line;
  80940. var lines = text.split('\n');
  80941. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  80942. var maxColor = 0;
  80943. for (var i = 0; i < lines.length; i++) {
  80944. line = lines[i];
  80945. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  80946. continue;
  80947. if (line.indexOf('#') === 0)
  80948. continue;
  80949. var words = line.split(" ");
  80950. if (size === 0) {
  80951. // Number of space + one
  80952. size = words.length;
  80953. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  80954. tempData = new Float32Array(size * size * size * 4);
  80955. continue;
  80956. }
  80957. if (size != 0) {
  80958. var r = Math.max(parseInt(words[0]), 0);
  80959. var g = Math.max(parseInt(words[1]), 0);
  80960. var b = Math.max(parseInt(words[2]), 0);
  80961. maxColor = Math.max(r, maxColor);
  80962. maxColor = Math.max(g, maxColor);
  80963. maxColor = Math.max(b, maxColor);
  80964. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  80965. if (tempData) {
  80966. tempData[pixelStorageIndex + 0] = r;
  80967. tempData[pixelStorageIndex + 1] = g;
  80968. tempData[pixelStorageIndex + 2] = b;
  80969. }
  80970. pixelIndexSlice++;
  80971. if (pixelIndexSlice % size == 0) {
  80972. pixelIndexH++;
  80973. pixelIndexSlice = 0;
  80974. if (pixelIndexH % size == 0) {
  80975. pixelIndexW++;
  80976. pixelIndexH = 0;
  80977. }
  80978. }
  80979. }
  80980. }
  80981. if (tempData && data) {
  80982. for (var i = 0; i < tempData.length; i++) {
  80983. if (i > 0 && (i + 1) % 4 === 0) {
  80984. data[i] = 255;
  80985. }
  80986. else {
  80987. var value = tempData[i];
  80988. data[i] = (value / maxColor * 255);
  80989. }
  80990. }
  80991. }
  80992. if (texture.is3D) {
  80993. texture.updateSize(size, size, size);
  80994. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80995. }
  80996. else {
  80997. texture.updateSize(size * size, size);
  80998. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80999. }
  81000. };
  81001. var scene = this.getScene();
  81002. if (scene) {
  81003. scene._loadFile(this.url, callback);
  81004. }
  81005. else {
  81006. this._engine._loadFile(this.url, callback);
  81007. }
  81008. return this._texture;
  81009. };
  81010. /**
  81011. * Starts the loading process of the texture.
  81012. */
  81013. ColorGradingTexture.prototype.loadTexture = function () {
  81014. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  81015. this.load3dlTexture();
  81016. }
  81017. };
  81018. /**
  81019. * Clones the color gradind texture.
  81020. */
  81021. ColorGradingTexture.prototype.clone = function () {
  81022. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  81023. // Base texture
  81024. newTexture.level = this.level;
  81025. return newTexture;
  81026. };
  81027. /**
  81028. * Called during delayed load for textures.
  81029. */
  81030. ColorGradingTexture.prototype.delayLoad = function () {
  81031. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81032. return;
  81033. }
  81034. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81035. this._texture = this._getFromCache(this.url, true);
  81036. if (!this._texture) {
  81037. this.loadTexture();
  81038. }
  81039. };
  81040. /**
  81041. * Parses a color grading texture serialized by Babylon.
  81042. * @param parsedTexture The texture information being parsedTexture
  81043. * @param scene The scene to load the texture in
  81044. * @param rootUrl The root url of the data assets to load
  81045. * @return A color gradind texture
  81046. */
  81047. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81048. var texture = null;
  81049. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81050. texture = new ColorGradingTexture(parsedTexture.name, scene);
  81051. texture.name = parsedTexture.name;
  81052. texture.level = parsedTexture.level;
  81053. }
  81054. return texture;
  81055. };
  81056. /**
  81057. * Serializes the LUT texture to json format.
  81058. */
  81059. ColorGradingTexture.prototype.serialize = function () {
  81060. if (!this.name) {
  81061. return null;
  81062. }
  81063. var serializationObject = {};
  81064. serializationObject.name = this.name;
  81065. serializationObject.level = this.level;
  81066. serializationObject.customType = "BABYLON.ColorGradingTexture";
  81067. return serializationObject;
  81068. };
  81069. /**
  81070. * Empty line regex stored for GC.
  81071. */
  81072. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  81073. return ColorGradingTexture;
  81074. }(BABYLON.BaseTexture));
  81075. BABYLON.ColorGradingTexture = ColorGradingTexture;
  81076. })(BABYLON || (BABYLON = {}));
  81077. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  81078. var BABYLON;
  81079. (function (BABYLON) {
  81080. /**
  81081. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  81082. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  81083. * 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;
  81084. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  81085. */
  81086. var ColorCurves = /** @class */ (function () {
  81087. function ColorCurves() {
  81088. this._dirty = true;
  81089. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  81090. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  81091. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81092. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  81093. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  81094. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  81095. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  81096. this._globalHue = 30;
  81097. this._globalDensity = 0;
  81098. this._globalSaturation = 0;
  81099. this._globalExposure = 0;
  81100. this._highlightsHue = 30;
  81101. this._highlightsDensity = 0;
  81102. this._highlightsSaturation = 0;
  81103. this._highlightsExposure = 0;
  81104. this._midtonesHue = 30;
  81105. this._midtonesDensity = 0;
  81106. this._midtonesSaturation = 0;
  81107. this._midtonesExposure = 0;
  81108. this._shadowsHue = 30;
  81109. this._shadowsDensity = 0;
  81110. this._shadowsSaturation = 0;
  81111. this._shadowsExposure = 0;
  81112. }
  81113. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  81114. /**
  81115. * Gets the global Hue value.
  81116. * 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).
  81117. */
  81118. get: function () {
  81119. return this._globalHue;
  81120. },
  81121. /**
  81122. * Sets the global Hue value.
  81123. * 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).
  81124. */
  81125. set: function (value) {
  81126. this._globalHue = value;
  81127. this._dirty = true;
  81128. },
  81129. enumerable: true,
  81130. configurable: true
  81131. });
  81132. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  81133. /**
  81134. * Gets the global Density value.
  81135. * 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.
  81136. * Values less than zero provide a filter of opposite hue.
  81137. */
  81138. get: function () {
  81139. return this._globalDensity;
  81140. },
  81141. /**
  81142. * Sets the global Density value.
  81143. * 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.
  81144. * Values less than zero provide a filter of opposite hue.
  81145. */
  81146. set: function (value) {
  81147. this._globalDensity = value;
  81148. this._dirty = true;
  81149. },
  81150. enumerable: true,
  81151. configurable: true
  81152. });
  81153. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  81154. /**
  81155. * Gets the global Saturation value.
  81156. * 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.
  81157. */
  81158. get: function () {
  81159. return this._globalSaturation;
  81160. },
  81161. /**
  81162. * Sets the global Saturation value.
  81163. * 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.
  81164. */
  81165. set: function (value) {
  81166. this._globalSaturation = value;
  81167. this._dirty = true;
  81168. },
  81169. enumerable: true,
  81170. configurable: true
  81171. });
  81172. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  81173. /**
  81174. * Gets the global Exposure value.
  81175. * 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.
  81176. */
  81177. get: function () {
  81178. return this._globalExposure;
  81179. },
  81180. /**
  81181. * Sets the global Exposure value.
  81182. * 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.
  81183. */
  81184. set: function (value) {
  81185. this._globalExposure = value;
  81186. this._dirty = true;
  81187. },
  81188. enumerable: true,
  81189. configurable: true
  81190. });
  81191. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  81192. /**
  81193. * Gets the highlights Hue value.
  81194. * 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).
  81195. */
  81196. get: function () {
  81197. return this._highlightsHue;
  81198. },
  81199. /**
  81200. * Sets the highlights Hue value.
  81201. * 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).
  81202. */
  81203. set: function (value) {
  81204. this._highlightsHue = value;
  81205. this._dirty = true;
  81206. },
  81207. enumerable: true,
  81208. configurable: true
  81209. });
  81210. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  81211. /**
  81212. * Gets the highlights Density value.
  81213. * 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.
  81214. * Values less than zero provide a filter of opposite hue.
  81215. */
  81216. get: function () {
  81217. return this._highlightsDensity;
  81218. },
  81219. /**
  81220. * Sets the highlights Density value.
  81221. * 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.
  81222. * Values less than zero provide a filter of opposite hue.
  81223. */
  81224. set: function (value) {
  81225. this._highlightsDensity = value;
  81226. this._dirty = true;
  81227. },
  81228. enumerable: true,
  81229. configurable: true
  81230. });
  81231. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  81232. /**
  81233. * Gets the highlights Saturation value.
  81234. * 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.
  81235. */
  81236. get: function () {
  81237. return this._highlightsSaturation;
  81238. },
  81239. /**
  81240. * Sets the highlights Saturation value.
  81241. * 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.
  81242. */
  81243. set: function (value) {
  81244. this._highlightsSaturation = value;
  81245. this._dirty = true;
  81246. },
  81247. enumerable: true,
  81248. configurable: true
  81249. });
  81250. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  81251. /**
  81252. * Gets the highlights Exposure value.
  81253. * 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.
  81254. */
  81255. get: function () {
  81256. return this._highlightsExposure;
  81257. },
  81258. /**
  81259. * Sets the highlights Exposure value.
  81260. * 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.
  81261. */
  81262. set: function (value) {
  81263. this._highlightsExposure = value;
  81264. this._dirty = true;
  81265. },
  81266. enumerable: true,
  81267. configurable: true
  81268. });
  81269. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  81270. /**
  81271. * Gets the midtones Hue value.
  81272. * 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).
  81273. */
  81274. get: function () {
  81275. return this._midtonesHue;
  81276. },
  81277. /**
  81278. * Sets the midtones Hue value.
  81279. * 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).
  81280. */
  81281. set: function (value) {
  81282. this._midtonesHue = value;
  81283. this._dirty = true;
  81284. },
  81285. enumerable: true,
  81286. configurable: true
  81287. });
  81288. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  81289. /**
  81290. * Gets the midtones Density value.
  81291. * 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.
  81292. * Values less than zero provide a filter of opposite hue.
  81293. */
  81294. get: function () {
  81295. return this._midtonesDensity;
  81296. },
  81297. /**
  81298. * Sets the midtones Density value.
  81299. * 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.
  81300. * Values less than zero provide a filter of opposite hue.
  81301. */
  81302. set: function (value) {
  81303. this._midtonesDensity = value;
  81304. this._dirty = true;
  81305. },
  81306. enumerable: true,
  81307. configurable: true
  81308. });
  81309. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  81310. /**
  81311. * Gets the midtones Saturation value.
  81312. * 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.
  81313. */
  81314. get: function () {
  81315. return this._midtonesSaturation;
  81316. },
  81317. /**
  81318. * Sets the midtones Saturation value.
  81319. * 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.
  81320. */
  81321. set: function (value) {
  81322. this._midtonesSaturation = value;
  81323. this._dirty = true;
  81324. },
  81325. enumerable: true,
  81326. configurable: true
  81327. });
  81328. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  81329. /**
  81330. * Gets the midtones Exposure value.
  81331. * 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.
  81332. */
  81333. get: function () {
  81334. return this._midtonesExposure;
  81335. },
  81336. /**
  81337. * Sets the midtones Exposure value.
  81338. * 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.
  81339. */
  81340. set: function (value) {
  81341. this._midtonesExposure = value;
  81342. this._dirty = true;
  81343. },
  81344. enumerable: true,
  81345. configurable: true
  81346. });
  81347. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  81348. /**
  81349. * Gets the shadows Hue value.
  81350. * 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).
  81351. */
  81352. get: function () {
  81353. return this._shadowsHue;
  81354. },
  81355. /**
  81356. * Sets the shadows Hue value.
  81357. * 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).
  81358. */
  81359. set: function (value) {
  81360. this._shadowsHue = value;
  81361. this._dirty = true;
  81362. },
  81363. enumerable: true,
  81364. configurable: true
  81365. });
  81366. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  81367. /**
  81368. * Gets the shadows Density value.
  81369. * 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.
  81370. * Values less than zero provide a filter of opposite hue.
  81371. */
  81372. get: function () {
  81373. return this._shadowsDensity;
  81374. },
  81375. /**
  81376. * Sets the shadows Density value.
  81377. * 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.
  81378. * Values less than zero provide a filter of opposite hue.
  81379. */
  81380. set: function (value) {
  81381. this._shadowsDensity = value;
  81382. this._dirty = true;
  81383. },
  81384. enumerable: true,
  81385. configurable: true
  81386. });
  81387. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  81388. /**
  81389. * Gets the shadows Saturation value.
  81390. * 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.
  81391. */
  81392. get: function () {
  81393. return this._shadowsSaturation;
  81394. },
  81395. /**
  81396. * Sets the shadows Saturation value.
  81397. * 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.
  81398. */
  81399. set: function (value) {
  81400. this._shadowsSaturation = value;
  81401. this._dirty = true;
  81402. },
  81403. enumerable: true,
  81404. configurable: true
  81405. });
  81406. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  81407. /**
  81408. * Gets the shadows Exposure value.
  81409. * 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.
  81410. */
  81411. get: function () {
  81412. return this._shadowsExposure;
  81413. },
  81414. /**
  81415. * Sets the shadows Exposure value.
  81416. * 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.
  81417. */
  81418. set: function (value) {
  81419. this._shadowsExposure = value;
  81420. this._dirty = true;
  81421. },
  81422. enumerable: true,
  81423. configurable: true
  81424. });
  81425. ColorCurves.prototype.getClassName = function () {
  81426. return "ColorCurves";
  81427. };
  81428. /**
  81429. * Binds the color curves to the shader.
  81430. * @param colorCurves The color curve to bind
  81431. * @param effect The effect to bind to
  81432. */
  81433. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  81434. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  81435. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  81436. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  81437. if (colorCurves._dirty) {
  81438. colorCurves._dirty = false;
  81439. // Fill in global info.
  81440. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  81441. // Compute highlights info.
  81442. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  81443. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  81444. // Compute midtones info.
  81445. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  81446. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  81447. // Compute shadows info.
  81448. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  81449. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  81450. // Compute deltas (neutral is midtones).
  81451. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  81452. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  81453. }
  81454. if (effect) {
  81455. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  81456. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  81457. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  81458. }
  81459. };
  81460. /**
  81461. * Prepare the list of uniforms associated with the ColorCurves effects.
  81462. * @param uniformsList The list of uniforms used in the effect
  81463. */
  81464. ColorCurves.PrepareUniforms = function (uniformsList) {
  81465. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  81466. };
  81467. /**
  81468. * Returns color grading data based on a hue, density, saturation and exposure value.
  81469. * @param filterHue The hue of the color filter.
  81470. * @param filterDensity The density of the color filter.
  81471. * @param saturation The saturation.
  81472. * @param exposure The exposure.
  81473. * @param result The result data container.
  81474. */
  81475. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  81476. if (hue == null) {
  81477. return;
  81478. }
  81479. hue = ColorCurves.clamp(hue, 0, 360);
  81480. density = ColorCurves.clamp(density, -100, 100);
  81481. saturation = ColorCurves.clamp(saturation, -100, 100);
  81482. exposure = ColorCurves.clamp(exposure, -100, 100);
  81483. // Remap the slider/config filter density with non-linear mapping and also scale by half
  81484. // so that the maximum filter density is only 50% control. This provides fine control
  81485. // for small values and reasonable range.
  81486. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  81487. density *= 0.5;
  81488. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  81489. if (density < 0) {
  81490. density *= -1;
  81491. hue = (hue + 180) % 360;
  81492. }
  81493. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  81494. result.scaleToRef(2, result);
  81495. result.a = 1 + 0.01 * saturation;
  81496. };
  81497. /**
  81498. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  81499. * @param value The input slider value in range [-100,100].
  81500. * @returns Adjusted value.
  81501. */
  81502. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  81503. value /= 100;
  81504. var x = Math.abs(value);
  81505. x = Math.pow(x, 2);
  81506. if (value < 0) {
  81507. x *= -1;
  81508. }
  81509. x *= 100;
  81510. return x;
  81511. };
  81512. /**
  81513. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  81514. * @param hue The hue (H) input.
  81515. * @param saturation The saturation (S) input.
  81516. * @param brightness The brightness (B) input.
  81517. * @result An RGBA color represented as Vector4.
  81518. */
  81519. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  81520. var h = ColorCurves.clamp(hue, 0, 360);
  81521. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  81522. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  81523. if (s === 0) {
  81524. result.r = v;
  81525. result.g = v;
  81526. result.b = v;
  81527. }
  81528. else {
  81529. // sector 0 to 5
  81530. h /= 60;
  81531. var i = Math.floor(h);
  81532. // fractional part of h
  81533. var f = h - i;
  81534. var p = v * (1 - s);
  81535. var q = v * (1 - s * f);
  81536. var t = v * (1 - s * (1 - f));
  81537. switch (i) {
  81538. case 0:
  81539. result.r = v;
  81540. result.g = t;
  81541. result.b = p;
  81542. break;
  81543. case 1:
  81544. result.r = q;
  81545. result.g = v;
  81546. result.b = p;
  81547. break;
  81548. case 2:
  81549. result.r = p;
  81550. result.g = v;
  81551. result.b = t;
  81552. break;
  81553. case 3:
  81554. result.r = p;
  81555. result.g = q;
  81556. result.b = v;
  81557. break;
  81558. case 4:
  81559. result.r = t;
  81560. result.g = p;
  81561. result.b = v;
  81562. break;
  81563. default: // case 5:
  81564. result.r = v;
  81565. result.g = p;
  81566. result.b = q;
  81567. break;
  81568. }
  81569. }
  81570. result.a = 1;
  81571. };
  81572. /**
  81573. * Returns a value clamped between min and max
  81574. * @param value The value to clamp
  81575. * @param min The minimum of value
  81576. * @param max The maximum of value
  81577. * @returns The clamped value.
  81578. */
  81579. ColorCurves.clamp = function (value, min, max) {
  81580. return Math.min(Math.max(value, min), max);
  81581. };
  81582. /**
  81583. * Clones the current color curve instance.
  81584. * @return The cloned curves
  81585. */
  81586. ColorCurves.prototype.clone = function () {
  81587. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  81588. };
  81589. /**
  81590. * Serializes the current color curve instance to a json representation.
  81591. * @return a JSON representation
  81592. */
  81593. ColorCurves.prototype.serialize = function () {
  81594. return BABYLON.SerializationHelper.Serialize(this);
  81595. };
  81596. /**
  81597. * Parses the color curve from a json representation.
  81598. * @param source the JSON source to parse
  81599. * @return The parsed curves
  81600. */
  81601. ColorCurves.Parse = function (source) {
  81602. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  81603. };
  81604. __decorate([
  81605. BABYLON.serialize()
  81606. ], ColorCurves.prototype, "_globalHue", void 0);
  81607. __decorate([
  81608. BABYLON.serialize()
  81609. ], ColorCurves.prototype, "_globalDensity", void 0);
  81610. __decorate([
  81611. BABYLON.serialize()
  81612. ], ColorCurves.prototype, "_globalSaturation", void 0);
  81613. __decorate([
  81614. BABYLON.serialize()
  81615. ], ColorCurves.prototype, "_globalExposure", void 0);
  81616. __decorate([
  81617. BABYLON.serialize()
  81618. ], ColorCurves.prototype, "_highlightsHue", void 0);
  81619. __decorate([
  81620. BABYLON.serialize()
  81621. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  81622. __decorate([
  81623. BABYLON.serialize()
  81624. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  81625. __decorate([
  81626. BABYLON.serialize()
  81627. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  81628. __decorate([
  81629. BABYLON.serialize()
  81630. ], ColorCurves.prototype, "_midtonesHue", void 0);
  81631. __decorate([
  81632. BABYLON.serialize()
  81633. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  81634. __decorate([
  81635. BABYLON.serialize()
  81636. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  81637. __decorate([
  81638. BABYLON.serialize()
  81639. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  81640. return ColorCurves;
  81641. }());
  81642. BABYLON.ColorCurves = ColorCurves;
  81643. })(BABYLON || (BABYLON = {}));
  81644. //# sourceMappingURL=babylon.colorCurves.js.map
  81645. var BABYLON;
  81646. (function (BABYLON) {
  81647. var RefractionPostProcess = /** @class */ (function (_super) {
  81648. __extends(RefractionPostProcess, _super);
  81649. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  81650. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  81651. _this.color = color;
  81652. _this.depth = depth;
  81653. _this.colorLevel = colorLevel;
  81654. _this._ownRefractionTexture = true;
  81655. _this.onActivateObservable.add(function (cam) {
  81656. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  81657. });
  81658. _this.onApplyObservable.add(function (effect) {
  81659. effect.setColor3("baseColor", _this.color);
  81660. effect.setFloat("depth", _this.depth);
  81661. effect.setFloat("colorLevel", _this.colorLevel);
  81662. effect.setTexture("refractionSampler", _this._refTexture);
  81663. });
  81664. return _this;
  81665. }
  81666. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  81667. /**
  81668. * Gets or sets the refraction texture
  81669. * Please note that you are responsible for disposing the texture if you set it manually
  81670. */
  81671. get: function () {
  81672. return this._refTexture;
  81673. },
  81674. set: function (value) {
  81675. if (this._refTexture && this._ownRefractionTexture) {
  81676. this._refTexture.dispose();
  81677. }
  81678. this._refTexture = value;
  81679. this._ownRefractionTexture = false;
  81680. },
  81681. enumerable: true,
  81682. configurable: true
  81683. });
  81684. // Methods
  81685. RefractionPostProcess.prototype.dispose = function (camera) {
  81686. if (this._refTexture && this._ownRefractionTexture) {
  81687. this._refTexture.dispose();
  81688. this._refTexture = null;
  81689. }
  81690. _super.prototype.dispose.call(this, camera);
  81691. };
  81692. return RefractionPostProcess;
  81693. }(BABYLON.PostProcess));
  81694. BABYLON.RefractionPostProcess = RefractionPostProcess;
  81695. })(BABYLON || (BABYLON = {}));
  81696. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  81697. var BABYLON;
  81698. (function (BABYLON) {
  81699. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  81700. __extends(BlackAndWhitePostProcess, _super);
  81701. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  81702. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  81703. _this.degree = 1;
  81704. _this.onApplyObservable.add(function (effect) {
  81705. effect.setFloat("degree", _this.degree);
  81706. });
  81707. return _this;
  81708. }
  81709. return BlackAndWhitePostProcess;
  81710. }(BABYLON.PostProcess));
  81711. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  81712. })(BABYLON || (BABYLON = {}));
  81713. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  81714. var BABYLON;
  81715. (function (BABYLON) {
  81716. /**
  81717. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  81718. * input texture to perform effects such as edge detection or sharpening
  81719. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  81720. */
  81721. var ConvolutionPostProcess = /** @class */ (function (_super) {
  81722. __extends(ConvolutionPostProcess, _super);
  81723. /**
  81724. * Creates a new instance ConvolutionPostProcess
  81725. * @param name The name of the effect.
  81726. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  81727. * @param options The required width/height ratio to downsize to before computing the render pass.
  81728. * @param camera The camera to apply the render pass to.
  81729. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81730. * @param engine The engine which the post process will be applied. (default: current engine)
  81731. * @param reusable If the post process can be reused on the same frame. (default: false)
  81732. * @param textureType Type of textures used when performing the post process. (default: 0)
  81733. */
  81734. function ConvolutionPostProcess(name,
  81735. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  81736. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  81737. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81738. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81739. _this.kernel = kernel;
  81740. _this.onApply = function (effect) {
  81741. effect.setFloat2("screenSize", _this.width, _this.height);
  81742. effect.setArray("kernel", _this.kernel);
  81743. };
  81744. return _this;
  81745. }
  81746. // Statics
  81747. /**
  81748. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81749. */
  81750. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  81751. /**
  81752. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81753. */
  81754. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  81755. /**
  81756. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81757. */
  81758. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  81759. /**
  81760. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81761. */
  81762. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  81763. /**
  81764. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81765. */
  81766. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  81767. /**
  81768. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81769. */
  81770. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  81771. return ConvolutionPostProcess;
  81772. }(BABYLON.PostProcess));
  81773. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  81774. })(BABYLON || (BABYLON = {}));
  81775. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  81776. var BABYLON;
  81777. (function (BABYLON) {
  81778. var FilterPostProcess = /** @class */ (function (_super) {
  81779. __extends(FilterPostProcess, _super);
  81780. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  81781. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  81782. _this.kernelMatrix = kernelMatrix;
  81783. _this.onApply = function (effect) {
  81784. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  81785. };
  81786. return _this;
  81787. }
  81788. return FilterPostProcess;
  81789. }(BABYLON.PostProcess));
  81790. BABYLON.FilterPostProcess = FilterPostProcess;
  81791. })(BABYLON || (BABYLON = {}));
  81792. //# sourceMappingURL=babylon.filterPostProcess.js.map
  81793. var BABYLON;
  81794. (function (BABYLON) {
  81795. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  81796. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  81797. __extends(VolumetricLightScatteringPostProcess, _super);
  81798. /**
  81799. * @constructor
  81800. * @param {string} name - The post-process name
  81801. * @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)
  81802. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  81803. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  81804. * @param {number} samples - The post-process quality, default 100
  81805. * @param {number} samplingMode - The post-process filtering mode
  81806. * @param {BABYLON.Engine} engine - The babylon engine
  81807. * @param {boolean} reusable - If the post-process is reusable
  81808. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  81809. */
  81810. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  81811. if (samples === void 0) { samples = 100; }
  81812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81813. 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;
  81814. _this._screenCoordinates = BABYLON.Vector2.Zero();
  81815. /**
  81816. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  81817. */
  81818. _this.customMeshPosition = BABYLON.Vector3.Zero();
  81819. /**
  81820. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  81821. */
  81822. _this.useCustomMeshPosition = false;
  81823. /**
  81824. * If the post-process should inverse the light scattering direction
  81825. */
  81826. _this.invert = true;
  81827. /**
  81828. * Array containing the excluded meshes not rendered in the internal pass
  81829. */
  81830. _this.excludedMeshes = new Array();
  81831. /**
  81832. * Controls the overall intensity of the post-process
  81833. */
  81834. _this.exposure = 0.3;
  81835. /**
  81836. * Dissipates each sample's contribution in range [0, 1]
  81837. */
  81838. _this.decay = 0.96815;
  81839. /**
  81840. * Controls the overall intensity of each sample
  81841. */
  81842. _this.weight = 0.58767;
  81843. /**
  81844. * Controls the density of each sample
  81845. */
  81846. _this.density = 0.926;
  81847. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  81848. engine = scene.getEngine();
  81849. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  81850. // Configure mesh
  81851. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  81852. // Configure
  81853. _this._createPass(scene, ratio.passRatio || ratio);
  81854. _this.onActivate = function (camera) {
  81855. if (!_this.isSupported) {
  81856. _this.dispose(camera);
  81857. }
  81858. _this.onActivate = null;
  81859. };
  81860. _this.onApplyObservable.add(function (effect) {
  81861. _this._updateMeshScreenCoordinates(scene);
  81862. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  81863. effect.setFloat("exposure", _this.exposure);
  81864. effect.setFloat("decay", _this.decay);
  81865. effect.setFloat("weight", _this.weight);
  81866. effect.setFloat("density", _this.density);
  81867. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  81868. });
  81869. return _this;
  81870. }
  81871. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  81872. get: function () {
  81873. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81874. return false;
  81875. },
  81876. set: function (useDiffuseColor) {
  81877. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81878. },
  81879. enumerable: true,
  81880. configurable: true
  81881. });
  81882. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  81883. return "VolumetricLightScatteringPostProcess";
  81884. };
  81885. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  81886. var mesh = subMesh.getMesh();
  81887. // Render this.mesh as default
  81888. if (mesh === this.mesh && mesh.material) {
  81889. return mesh.material.isReady(mesh);
  81890. }
  81891. var defines = [];
  81892. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81893. var material = subMesh.getMaterial();
  81894. // Alpha test
  81895. if (material) {
  81896. if (material.needAlphaTesting()) {
  81897. defines.push("#define ALPHATEST");
  81898. }
  81899. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81900. attribs.push(BABYLON.VertexBuffer.UVKind);
  81901. defines.push("#define UV1");
  81902. }
  81903. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81904. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81905. defines.push("#define UV2");
  81906. }
  81907. }
  81908. // Bones
  81909. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81910. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81911. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81912. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81913. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81914. }
  81915. else {
  81916. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81917. }
  81918. // Instances
  81919. if (useInstances) {
  81920. defines.push("#define INSTANCES");
  81921. attribs.push("world0");
  81922. attribs.push("world1");
  81923. attribs.push("world2");
  81924. attribs.push("world3");
  81925. }
  81926. // Get correct effect
  81927. var join = defines.join("\n");
  81928. if (this._cachedDefines !== join) {
  81929. this._cachedDefines = join;
  81930. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  81931. }
  81932. return this._volumetricLightScatteringPass.isReady();
  81933. };
  81934. /**
  81935. * Sets the new light position for light scattering effect
  81936. * @param {BABYLON.Vector3} The new custom light position
  81937. */
  81938. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  81939. this.customMeshPosition = position;
  81940. };
  81941. /**
  81942. * Returns the light position for light scattering effect
  81943. * @return {BABYLON.Vector3} The custom light position
  81944. */
  81945. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  81946. return this.customMeshPosition;
  81947. };
  81948. /**
  81949. * Disposes the internal assets and detaches the post-process from the camera
  81950. */
  81951. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  81952. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  81953. if (rttIndex !== -1) {
  81954. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  81955. }
  81956. this._volumetricLightScatteringRTT.dispose();
  81957. _super.prototype.dispose.call(this, camera);
  81958. };
  81959. /**
  81960. * Returns the render target texture used by the post-process
  81961. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  81962. */
  81963. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  81964. return this._volumetricLightScatteringRTT;
  81965. };
  81966. // Private methods
  81967. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  81968. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  81969. return true;
  81970. }
  81971. return false;
  81972. };
  81973. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  81974. var _this = this;
  81975. var engine = scene.getEngine();
  81976. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81977. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81978. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81979. this._volumetricLightScatteringRTT.renderList = null;
  81980. this._volumetricLightScatteringRTT.renderParticles = false;
  81981. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  81982. var camera = this.getCamera();
  81983. if (camera) {
  81984. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81985. }
  81986. else {
  81987. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81988. }
  81989. // Custom render function for submeshes
  81990. var renderSubMesh = function (subMesh) {
  81991. var mesh = subMesh.getRenderingMesh();
  81992. if (_this._meshExcluded(mesh)) {
  81993. return;
  81994. }
  81995. var material = subMesh.getMaterial();
  81996. if (!material) {
  81997. return;
  81998. }
  81999. var scene = mesh.getScene();
  82000. var engine = scene.getEngine();
  82001. // Culling
  82002. engine.setState(material.backFaceCulling);
  82003. // Managing instances
  82004. var batch = mesh._getInstancesRenderList(subMesh._id);
  82005. if (batch.mustReturn) {
  82006. return;
  82007. }
  82008. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82009. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  82010. var effect = _this._volumetricLightScatteringPass;
  82011. if (mesh === _this.mesh) {
  82012. if (subMesh.effect) {
  82013. effect = subMesh.effect;
  82014. }
  82015. else {
  82016. effect = material.getEffect();
  82017. }
  82018. }
  82019. engine.enableEffect(effect);
  82020. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  82021. if (mesh === _this.mesh) {
  82022. material.bind(mesh.getWorldMatrix(), mesh);
  82023. }
  82024. else {
  82025. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  82026. // Alpha test
  82027. if (material && material.needAlphaTesting()) {
  82028. var alphaTexture = material.getAlphaTestTexture();
  82029. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  82030. if (alphaTexture) {
  82031. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82032. }
  82033. }
  82034. // Bones
  82035. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82036. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82037. }
  82038. }
  82039. // Draw
  82040. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  82041. }
  82042. };
  82043. // Render target texture callbacks
  82044. var savedSceneClearColor;
  82045. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  82046. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  82047. savedSceneClearColor = scene.clearColor;
  82048. scene.clearColor = sceneClearColor;
  82049. });
  82050. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  82051. scene.clearColor = savedSceneClearColor;
  82052. });
  82053. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82054. var engine = scene.getEngine();
  82055. var index;
  82056. if (depthOnlySubMeshes.length) {
  82057. engine.setColorWrite(false);
  82058. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82059. renderSubMesh(depthOnlySubMeshes.data[index]);
  82060. }
  82061. engine.setColorWrite(true);
  82062. }
  82063. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82064. renderSubMesh(opaqueSubMeshes.data[index]);
  82065. }
  82066. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82067. renderSubMesh(alphaTestSubMeshes.data[index]);
  82068. }
  82069. if (transparentSubMeshes.length) {
  82070. // Sort sub meshes
  82071. for (index = 0; index < transparentSubMeshes.length; index++) {
  82072. var submesh = transparentSubMeshes.data[index];
  82073. var boundingInfo = submesh.getBoundingInfo();
  82074. if (boundingInfo && scene.activeCamera) {
  82075. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  82076. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  82077. }
  82078. }
  82079. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  82080. sortedArray.sort(function (a, b) {
  82081. // Alpha index first
  82082. if (a._alphaIndex > b._alphaIndex) {
  82083. return 1;
  82084. }
  82085. if (a._alphaIndex < b._alphaIndex) {
  82086. return -1;
  82087. }
  82088. // Then distance to camera
  82089. if (a._distanceToCamera < b._distanceToCamera) {
  82090. return 1;
  82091. }
  82092. if (a._distanceToCamera > b._distanceToCamera) {
  82093. return -1;
  82094. }
  82095. return 0;
  82096. });
  82097. // Render sub meshes
  82098. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  82099. for (index = 0; index < sortedArray.length; index++) {
  82100. renderSubMesh(sortedArray[index]);
  82101. }
  82102. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82103. }
  82104. };
  82105. };
  82106. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  82107. var transform = scene.getTransformMatrix();
  82108. var meshPosition;
  82109. if (this.useCustomMeshPosition) {
  82110. meshPosition = this.customMeshPosition;
  82111. }
  82112. else if (this.attachedNode) {
  82113. meshPosition = this.attachedNode.position;
  82114. }
  82115. else {
  82116. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  82117. }
  82118. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  82119. this._screenCoordinates.x = pos.x / this._viewPort.width;
  82120. this._screenCoordinates.y = pos.y / this._viewPort.height;
  82121. if (this.invert)
  82122. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  82123. };
  82124. // Static methods
  82125. /**
  82126. * Creates a default mesh for the Volumeric Light Scattering post-process
  82127. * @param {string} The mesh name
  82128. * @param {BABYLON.Scene} The scene where to create the mesh
  82129. * @return {BABYLON.Mesh} the default mesh
  82130. */
  82131. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  82132. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  82133. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  82134. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  82135. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  82136. mesh.material = material;
  82137. return mesh;
  82138. };
  82139. __decorate([
  82140. BABYLON.serializeAsVector3()
  82141. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  82142. __decorate([
  82143. BABYLON.serialize()
  82144. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  82145. __decorate([
  82146. BABYLON.serialize()
  82147. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  82148. __decorate([
  82149. BABYLON.serializeAsMeshReference()
  82150. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  82151. __decorate([
  82152. BABYLON.serialize()
  82153. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  82154. __decorate([
  82155. BABYLON.serialize()
  82156. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  82157. __decorate([
  82158. BABYLON.serialize()
  82159. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  82160. __decorate([
  82161. BABYLON.serialize()
  82162. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  82163. __decorate([
  82164. BABYLON.serialize()
  82165. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  82166. return VolumetricLightScatteringPostProcess;
  82167. }(BABYLON.PostProcess));
  82168. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  82169. })(BABYLON || (BABYLON = {}));
  82170. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  82171. //
  82172. // This post-process allows the modification of rendered colors by using
  82173. // a 'look-up table' (LUT). This effect is also called Color Grading.
  82174. //
  82175. // The object needs to be provided an url to a texture containing the color
  82176. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  82177. // Use an image editing software to tweak the LUT to match your needs.
  82178. //
  82179. // For an example of a color LUT, see here:
  82180. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  82181. // For explanations on color grading, see here:
  82182. // http://udn.epicgames.com/Three/ColorGrading.html
  82183. //
  82184. var BABYLON;
  82185. (function (BABYLON) {
  82186. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  82187. __extends(ColorCorrectionPostProcess, _super);
  82188. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  82189. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  82190. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82191. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  82192. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82193. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82194. _this.onApply = function (effect) {
  82195. effect.setTexture("colorTable", _this._colorTableTexture);
  82196. };
  82197. return _this;
  82198. }
  82199. return ColorCorrectionPostProcess;
  82200. }(BABYLON.PostProcess));
  82201. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  82202. })(BABYLON || (BABYLON = {}));
  82203. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  82204. var BABYLON;
  82205. (function (BABYLON) {
  82206. /** Defines operator used for tonemapping */
  82207. var TonemappingOperator;
  82208. (function (TonemappingOperator) {
  82209. /** Hable */
  82210. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  82211. /** Reinhard */
  82212. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  82213. /** HejiDawson */
  82214. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  82215. /** Photographic */
  82216. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  82217. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  82218. ;
  82219. /**
  82220. * Defines a post process to apply tone mapping
  82221. */
  82222. var TonemapPostProcess = /** @class */ (function (_super) {
  82223. __extends(TonemapPostProcess, _super);
  82224. /**
  82225. * Creates a new TonemapPostProcess
  82226. * @param name defines the name of the postprocess
  82227. * @param _operator defines the operator to use
  82228. * @param exposureAdjustment defines the required exposure adjustement
  82229. * @param camera defines the camera to use (can be null)
  82230. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  82231. * @param engine defines the hosting engine (can be ignore if camera is set)
  82232. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  82233. */
  82234. function TonemapPostProcess(name, _operator,
  82235. /** Defines the required exposure adjustement */
  82236. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  82237. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82238. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82239. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  82240. _this._operator = _operator;
  82241. _this.exposureAdjustment = exposureAdjustment;
  82242. var defines = "#define ";
  82243. if (_this._operator === TonemappingOperator.Hable)
  82244. defines += "HABLE_TONEMAPPING";
  82245. else if (_this._operator === TonemappingOperator.Reinhard)
  82246. defines += "REINHARD_TONEMAPPING";
  82247. else if (_this._operator === TonemappingOperator.HejiDawson)
  82248. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  82249. else if (_this._operator === TonemappingOperator.Photographic)
  82250. defines += "PHOTOGRAPHIC_TONEMAPPING";
  82251. //sadly a second call to create the effect.
  82252. _this.updateEffect(defines);
  82253. _this.onApply = function (effect) {
  82254. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  82255. };
  82256. return _this;
  82257. }
  82258. return TonemapPostProcess;
  82259. }(BABYLON.PostProcess));
  82260. BABYLON.TonemapPostProcess = TonemapPostProcess;
  82261. })(BABYLON || (BABYLON = {}));
  82262. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  82263. var BABYLON;
  82264. (function (BABYLON) {
  82265. var DisplayPassPostProcess = /** @class */ (function (_super) {
  82266. __extends(DisplayPassPostProcess, _super);
  82267. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  82268. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  82269. }
  82270. return DisplayPassPostProcess;
  82271. }(BABYLON.PostProcess));
  82272. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  82273. })(BABYLON || (BABYLON = {}));
  82274. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  82275. var BABYLON;
  82276. (function (BABYLON) {
  82277. var HighlightsPostProcess = /** @class */ (function (_super) {
  82278. __extends(HighlightsPostProcess, _super);
  82279. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82280. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82281. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  82282. }
  82283. return HighlightsPostProcess;
  82284. }(BABYLON.PostProcess));
  82285. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  82286. })(BABYLON || (BABYLON = {}));
  82287. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  82288. var BABYLON;
  82289. (function (BABYLON) {
  82290. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  82291. __extends(ImageProcessingPostProcess, _super);
  82292. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  82293. if (camera === void 0) { camera = null; }
  82294. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82295. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  82296. _this._fromLinearSpace = true;
  82297. /**
  82298. * Defines cache preventing GC.
  82299. */
  82300. _this._defines = {
  82301. IMAGEPROCESSING: false,
  82302. VIGNETTE: false,
  82303. VIGNETTEBLENDMODEMULTIPLY: false,
  82304. VIGNETTEBLENDMODEOPAQUE: false,
  82305. TONEMAPPING: false,
  82306. TONEMAPPING_ACES: false,
  82307. CONTRAST: false,
  82308. COLORCURVES: false,
  82309. COLORGRADING: false,
  82310. COLORGRADING3D: false,
  82311. FROMLINEARSPACE: false,
  82312. SAMPLER3DGREENDEPTH: false,
  82313. SAMPLER3DBGRMAP: false,
  82314. IMAGEPROCESSINGPOSTPROCESS: false,
  82315. EXPOSURE: false,
  82316. };
  82317. // Setup the configuration as forced by the constructor. This would then not force the
  82318. // scene materials output in linear space and let untouched the default forward pass.
  82319. if (imageProcessingConfiguration) {
  82320. imageProcessingConfiguration.applyByPostProcess = true;
  82321. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  82322. // This will cause the shader to be compiled
  82323. _this.fromLinearSpace = false;
  82324. }
  82325. // Setup the default processing configuration to the scene.
  82326. else {
  82327. _this._attachImageProcessingConfiguration(null, true);
  82328. _this.imageProcessingConfiguration.applyByPostProcess = true;
  82329. }
  82330. _this.onApply = function (effect) {
  82331. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  82332. };
  82333. return _this;
  82334. }
  82335. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  82336. /**
  82337. * Gets the image processing configuration used either in this material.
  82338. */
  82339. get: function () {
  82340. return this._imageProcessingConfiguration;
  82341. },
  82342. /**
  82343. * Sets the Default image processing configuration used either in the this material.
  82344. *
  82345. * If sets to null, the scene one is in use.
  82346. */
  82347. set: function (value) {
  82348. this._attachImageProcessingConfiguration(value);
  82349. },
  82350. enumerable: true,
  82351. configurable: true
  82352. });
  82353. /**
  82354. * Attaches a new image processing configuration to the PBR Material.
  82355. * @param configuration
  82356. */
  82357. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  82358. var _this = this;
  82359. if (doNotBuild === void 0) { doNotBuild = false; }
  82360. if (configuration === this._imageProcessingConfiguration) {
  82361. return;
  82362. }
  82363. // Detaches observer.
  82364. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82365. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82366. }
  82367. // Pick the scene configuration if needed.
  82368. if (!configuration) {
  82369. var scene = null;
  82370. var engine = this.getEngine();
  82371. var camera = this.getCamera();
  82372. if (camera) {
  82373. scene = camera.getScene();
  82374. }
  82375. else if (engine && engine.scenes) {
  82376. var scenes = engine.scenes;
  82377. scene = scenes[scenes.length - 1];
  82378. }
  82379. else {
  82380. scene = BABYLON.Engine.LastCreatedScene;
  82381. }
  82382. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  82383. }
  82384. else {
  82385. this._imageProcessingConfiguration = configuration;
  82386. }
  82387. // Attaches observer.
  82388. if (this._imageProcessingConfiguration) {
  82389. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82390. _this._updateParameters();
  82391. });
  82392. }
  82393. // Ensure the effect will be rebuilt.
  82394. if (!doNotBuild) {
  82395. this._updateParameters();
  82396. }
  82397. };
  82398. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  82399. /**
  82400. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82401. */
  82402. get: function () {
  82403. return this.imageProcessingConfiguration.colorCurves;
  82404. },
  82405. /**
  82406. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  82407. */
  82408. set: function (value) {
  82409. this.imageProcessingConfiguration.colorCurves = value;
  82410. },
  82411. enumerable: true,
  82412. configurable: true
  82413. });
  82414. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  82415. /**
  82416. * Gets wether the color curves effect is enabled.
  82417. */
  82418. get: function () {
  82419. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82420. },
  82421. /**
  82422. * Sets wether the color curves effect is enabled.
  82423. */
  82424. set: function (value) {
  82425. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82426. },
  82427. enumerable: true,
  82428. configurable: true
  82429. });
  82430. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  82431. /**
  82432. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82433. */
  82434. get: function () {
  82435. return this.imageProcessingConfiguration.colorGradingTexture;
  82436. },
  82437. /**
  82438. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  82439. */
  82440. set: function (value) {
  82441. this.imageProcessingConfiguration.colorGradingTexture = value;
  82442. },
  82443. enumerable: true,
  82444. configurable: true
  82445. });
  82446. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  82447. /**
  82448. * Gets wether the color grading effect is enabled.
  82449. */
  82450. get: function () {
  82451. return this.imageProcessingConfiguration.colorGradingEnabled;
  82452. },
  82453. /**
  82454. * Gets wether the color grading effect is enabled.
  82455. */
  82456. set: function (value) {
  82457. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82458. },
  82459. enumerable: true,
  82460. configurable: true
  82461. });
  82462. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  82463. /**
  82464. * Gets exposure used in the effect.
  82465. */
  82466. get: function () {
  82467. return this.imageProcessingConfiguration.exposure;
  82468. },
  82469. /**
  82470. * Sets exposure used in the effect.
  82471. */
  82472. set: function (value) {
  82473. this.imageProcessingConfiguration.exposure = value;
  82474. },
  82475. enumerable: true,
  82476. configurable: true
  82477. });
  82478. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  82479. /**
  82480. * Gets wether tonemapping is enabled or not.
  82481. */
  82482. get: function () {
  82483. return this._imageProcessingConfiguration.toneMappingEnabled;
  82484. },
  82485. /**
  82486. * Sets wether tonemapping is enabled or not
  82487. */
  82488. set: function (value) {
  82489. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82490. },
  82491. enumerable: true,
  82492. configurable: true
  82493. });
  82494. ;
  82495. ;
  82496. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  82497. /**
  82498. * Gets contrast used in the effect.
  82499. */
  82500. get: function () {
  82501. return this.imageProcessingConfiguration.contrast;
  82502. },
  82503. /**
  82504. * Sets contrast used in the effect.
  82505. */
  82506. set: function (value) {
  82507. this.imageProcessingConfiguration.contrast = value;
  82508. },
  82509. enumerable: true,
  82510. configurable: true
  82511. });
  82512. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  82513. /**
  82514. * Gets Vignette stretch size.
  82515. */
  82516. get: function () {
  82517. return this.imageProcessingConfiguration.vignetteStretch;
  82518. },
  82519. /**
  82520. * Sets Vignette stretch size.
  82521. */
  82522. set: function (value) {
  82523. this.imageProcessingConfiguration.vignetteStretch = value;
  82524. },
  82525. enumerable: true,
  82526. configurable: true
  82527. });
  82528. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  82529. /**
  82530. * Gets Vignette centre X Offset.
  82531. */
  82532. get: function () {
  82533. return this.imageProcessingConfiguration.vignetteCentreX;
  82534. },
  82535. /**
  82536. * Sets Vignette centre X Offset.
  82537. */
  82538. set: function (value) {
  82539. this.imageProcessingConfiguration.vignetteCentreX = value;
  82540. },
  82541. enumerable: true,
  82542. configurable: true
  82543. });
  82544. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  82545. /**
  82546. * Gets Vignette centre Y Offset.
  82547. */
  82548. get: function () {
  82549. return this.imageProcessingConfiguration.vignetteCentreY;
  82550. },
  82551. /**
  82552. * Sets Vignette centre Y Offset.
  82553. */
  82554. set: function (value) {
  82555. this.imageProcessingConfiguration.vignetteCentreY = value;
  82556. },
  82557. enumerable: true,
  82558. configurable: true
  82559. });
  82560. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  82561. /**
  82562. * Gets Vignette weight or intensity of the vignette effect.
  82563. */
  82564. get: function () {
  82565. return this.imageProcessingConfiguration.vignetteWeight;
  82566. },
  82567. /**
  82568. * Sets Vignette weight or intensity of the vignette effect.
  82569. */
  82570. set: function (value) {
  82571. this.imageProcessingConfiguration.vignetteWeight = value;
  82572. },
  82573. enumerable: true,
  82574. configurable: true
  82575. });
  82576. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  82577. /**
  82578. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82579. * if vignetteEnabled is set to true.
  82580. */
  82581. get: function () {
  82582. return this.imageProcessingConfiguration.vignetteColor;
  82583. },
  82584. /**
  82585. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82586. * if vignetteEnabled is set to true.
  82587. */
  82588. set: function (value) {
  82589. this.imageProcessingConfiguration.vignetteColor = value;
  82590. },
  82591. enumerable: true,
  82592. configurable: true
  82593. });
  82594. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  82595. /**
  82596. * Gets Camera field of view used by the Vignette effect.
  82597. */
  82598. get: function () {
  82599. return this.imageProcessingConfiguration.vignetteCameraFov;
  82600. },
  82601. /**
  82602. * Sets Camera field of view used by the Vignette effect.
  82603. */
  82604. set: function (value) {
  82605. this.imageProcessingConfiguration.vignetteCameraFov = value;
  82606. },
  82607. enumerable: true,
  82608. configurable: true
  82609. });
  82610. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  82611. /**
  82612. * Gets the vignette blend mode allowing different kind of effect.
  82613. */
  82614. get: function () {
  82615. return this.imageProcessingConfiguration.vignetteBlendMode;
  82616. },
  82617. /**
  82618. * Sets the vignette blend mode allowing different kind of effect.
  82619. */
  82620. set: function (value) {
  82621. this.imageProcessingConfiguration.vignetteBlendMode = value;
  82622. },
  82623. enumerable: true,
  82624. configurable: true
  82625. });
  82626. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  82627. /**
  82628. * Gets wether the vignette effect is enabled.
  82629. */
  82630. get: function () {
  82631. return this.imageProcessingConfiguration.vignetteEnabled;
  82632. },
  82633. /**
  82634. * Sets wether the vignette effect is enabled.
  82635. */
  82636. set: function (value) {
  82637. this.imageProcessingConfiguration.vignetteEnabled = value;
  82638. },
  82639. enumerable: true,
  82640. configurable: true
  82641. });
  82642. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  82643. /**
  82644. * Gets wether the input of the processing is in Gamma or Linear Space.
  82645. */
  82646. get: function () {
  82647. return this._fromLinearSpace;
  82648. },
  82649. /**
  82650. * Sets wether the input of the processing is in Gamma or Linear Space.
  82651. */
  82652. set: function (value) {
  82653. if (this._fromLinearSpace === value) {
  82654. return;
  82655. }
  82656. this._fromLinearSpace = value;
  82657. this._updateParameters();
  82658. },
  82659. enumerable: true,
  82660. configurable: true
  82661. });
  82662. ImageProcessingPostProcess.prototype.getClassName = function () {
  82663. return "ImageProcessingPostProcess";
  82664. };
  82665. ImageProcessingPostProcess.prototype._updateParameters = function () {
  82666. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  82667. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  82668. var defines = "";
  82669. for (var define in this._defines) {
  82670. if (this._defines[define]) {
  82671. defines += "#define " + define + ";\r\n";
  82672. }
  82673. }
  82674. var samplers = ["textureSampler"];
  82675. var uniforms = ["scale"];
  82676. if (BABYLON.ImageProcessingConfiguration) {
  82677. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  82678. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  82679. }
  82680. this.updateEffect(defines, uniforms, samplers);
  82681. };
  82682. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  82683. _super.prototype.dispose.call(this, camera);
  82684. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82685. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82686. }
  82687. if (this._imageProcessingConfiguration) {
  82688. this.imageProcessingConfiguration.applyByPostProcess = false;
  82689. }
  82690. };
  82691. __decorate([
  82692. BABYLON.serialize()
  82693. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  82694. return ImageProcessingPostProcess;
  82695. }(BABYLON.PostProcess));
  82696. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  82697. })(BABYLON || (BABYLON = {}));
  82698. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  82699. var BABYLON;
  82700. (function (BABYLON) {
  82701. /**
  82702. * Class used to store bone information
  82703. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82704. */
  82705. var Bone = /** @class */ (function (_super) {
  82706. __extends(Bone, _super);
  82707. /**
  82708. * Create a new bone
  82709. * @param name defines the bone name
  82710. * @param skeleton defines the parent skeleton
  82711. * @param parentBone defines the parent (can be null if the bone is the root)
  82712. * @param localMatrix defines the local matrix
  82713. * @param restPose defines the rest pose matrix
  82714. * @param baseMatrix defines the base matrix
  82715. * @param index defines index of the bone in the hiearchy
  82716. */
  82717. function Bone(
  82718. /**
  82719. * defines the bone name
  82720. */
  82721. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  82722. if (parentBone === void 0) { parentBone = null; }
  82723. if (localMatrix === void 0) { localMatrix = null; }
  82724. if (restPose === void 0) { restPose = null; }
  82725. if (baseMatrix === void 0) { baseMatrix = null; }
  82726. if (index === void 0) { index = null; }
  82727. var _this = _super.call(this, name, skeleton.getScene()) || this;
  82728. _this.name = name;
  82729. /**
  82730. * Gets the list of child bones
  82731. */
  82732. _this.children = new Array();
  82733. /** Gets the animations associated with this bone */
  82734. _this.animations = new Array();
  82735. /**
  82736. * @hidden Internal only
  82737. * Set this value to map this bone to a different index in the transform matrices
  82738. * Set this value to -1 to exclude the bone from the transform matrices
  82739. */
  82740. _this._index = null;
  82741. _this._absoluteTransform = new BABYLON.Matrix();
  82742. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  82743. _this._scalingDeterminant = 1;
  82744. _this._worldTransform = new BABYLON.Matrix();
  82745. _this._needToDecompose = true;
  82746. _this._needToCompose = false;
  82747. _this._skeleton = skeleton;
  82748. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  82749. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  82750. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  82751. _this._index = index;
  82752. skeleton.bones.push(_this);
  82753. _this.setParent(parentBone, false);
  82754. if (baseMatrix || localMatrix) {
  82755. _this._updateDifferenceMatrix();
  82756. }
  82757. return _this;
  82758. }
  82759. Object.defineProperty(Bone.prototype, "_matrix", {
  82760. /** @hidden */
  82761. get: function () {
  82762. this._compose();
  82763. return this._localMatrix;
  82764. },
  82765. /** @hidden */
  82766. set: function (value) {
  82767. this._localMatrix.copyFrom(value);
  82768. this._needToDecompose = true;
  82769. },
  82770. enumerable: true,
  82771. configurable: true
  82772. });
  82773. // Members
  82774. /**
  82775. * Gets the parent skeleton
  82776. * @returns a skeleton
  82777. */
  82778. Bone.prototype.getSkeleton = function () {
  82779. return this._skeleton;
  82780. };
  82781. /**
  82782. * Gets parent bone
  82783. * @returns a bone or null if the bone is the root of the bone hierarchy
  82784. */
  82785. Bone.prototype.getParent = function () {
  82786. return this._parent;
  82787. };
  82788. /**
  82789. * Sets the parent bone
  82790. * @param parent defines the parent (can be null if the bone is the root)
  82791. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82792. */
  82793. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  82794. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82795. if (this._parent === parent) {
  82796. return;
  82797. }
  82798. if (this._parent) {
  82799. var index = this._parent.children.indexOf(this);
  82800. if (index !== -1) {
  82801. this._parent.children.splice(index, 1);
  82802. }
  82803. }
  82804. this._parent = parent;
  82805. if (this._parent) {
  82806. this._parent.children.push(this);
  82807. }
  82808. if (updateDifferenceMatrix) {
  82809. this._updateDifferenceMatrix();
  82810. }
  82811. this.markAsDirty();
  82812. };
  82813. /**
  82814. * Gets the local matrix
  82815. * @returns a matrix
  82816. */
  82817. Bone.prototype.getLocalMatrix = function () {
  82818. this._compose();
  82819. return this._localMatrix;
  82820. };
  82821. /**
  82822. * Gets the base matrix (initial matrix which remains unchanged)
  82823. * @returns a matrix
  82824. */
  82825. Bone.prototype.getBaseMatrix = function () {
  82826. return this._baseMatrix;
  82827. };
  82828. /**
  82829. * Gets the rest pose matrix
  82830. * @returns a matrix
  82831. */
  82832. Bone.prototype.getRestPose = function () {
  82833. return this._restPose;
  82834. };
  82835. /**
  82836. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  82837. */
  82838. Bone.prototype.getWorldMatrix = function () {
  82839. return this._worldTransform;
  82840. };
  82841. /**
  82842. * Sets the local matrix to rest pose matrix
  82843. */
  82844. Bone.prototype.returnToRest = function () {
  82845. this.updateMatrix(this._restPose.clone());
  82846. };
  82847. /**
  82848. * Gets the inverse of the absolute transform matrix.
  82849. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  82850. * @returns a matrix
  82851. */
  82852. Bone.prototype.getInvertedAbsoluteTransform = function () {
  82853. return this._invertedAbsoluteTransform;
  82854. };
  82855. /**
  82856. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  82857. * @returns a matrix
  82858. */
  82859. Bone.prototype.getAbsoluteTransform = function () {
  82860. return this._absoluteTransform;
  82861. };
  82862. Object.defineProperty(Bone.prototype, "position", {
  82863. // Properties (matches AbstractMesh properties)
  82864. /** Gets or sets current position (in local space) */
  82865. get: function () {
  82866. this._decompose();
  82867. return this._localPosition;
  82868. },
  82869. set: function (newPosition) {
  82870. this._decompose();
  82871. this._localPosition.copyFrom(newPosition);
  82872. this._markAsDirtyAndCompose();
  82873. },
  82874. enumerable: true,
  82875. configurable: true
  82876. });
  82877. Object.defineProperty(Bone.prototype, "rotation", {
  82878. /** Gets or sets current rotation (in local space) */
  82879. get: function () {
  82880. return this.getRotation();
  82881. },
  82882. set: function (newRotation) {
  82883. this.setRotation(newRotation);
  82884. },
  82885. enumerable: true,
  82886. configurable: true
  82887. });
  82888. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  82889. /** Gets or sets current rotation quaternion (in local space) */
  82890. get: function () {
  82891. this._decompose();
  82892. return this._localRotation;
  82893. },
  82894. set: function (newRotation) {
  82895. this.setRotationQuaternion(newRotation);
  82896. },
  82897. enumerable: true,
  82898. configurable: true
  82899. });
  82900. Object.defineProperty(Bone.prototype, "scaling", {
  82901. /** Gets or sets current scaling (in local space) */
  82902. get: function () {
  82903. return this.getScale();
  82904. },
  82905. set: function (newScaling) {
  82906. this.setScale(newScaling);
  82907. },
  82908. enumerable: true,
  82909. configurable: true
  82910. });
  82911. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  82912. /**
  82913. * Gets the animation properties override
  82914. */
  82915. get: function () {
  82916. return this._skeleton.animationPropertiesOverride;
  82917. },
  82918. enumerable: true,
  82919. configurable: true
  82920. });
  82921. // Methods
  82922. Bone.prototype._decompose = function () {
  82923. if (!this._needToDecompose) {
  82924. return;
  82925. }
  82926. this._needToDecompose = false;
  82927. if (!this._localScaling) {
  82928. this._localScaling = BABYLON.Vector3.Zero();
  82929. this._localRotation = BABYLON.Quaternion.Zero();
  82930. this._localPosition = BABYLON.Vector3.Zero();
  82931. }
  82932. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  82933. };
  82934. Bone.prototype._compose = function () {
  82935. if (!this._needToCompose) {
  82936. return;
  82937. }
  82938. this._needToCompose = false;
  82939. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  82940. };
  82941. /**
  82942. * Update the base and local matrices
  82943. * @param matrix defines the new base or local matrix
  82944. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82945. * @param updateLocalMatrix defines if the local matrix should be updated
  82946. */
  82947. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  82948. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82949. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  82950. this._baseMatrix.copyFrom(matrix);
  82951. if (updateDifferenceMatrix) {
  82952. this._updateDifferenceMatrix();
  82953. }
  82954. if (updateLocalMatrix) {
  82955. this._localMatrix.copyFrom(matrix);
  82956. this._markAsDirtyAndDecompose();
  82957. }
  82958. else {
  82959. this.markAsDirty();
  82960. }
  82961. };
  82962. /** @hidden */
  82963. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  82964. if (updateChildren === void 0) { updateChildren = true; }
  82965. if (!rootMatrix) {
  82966. rootMatrix = this._baseMatrix;
  82967. }
  82968. if (this._parent) {
  82969. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82970. }
  82971. else {
  82972. this._absoluteTransform.copyFrom(rootMatrix);
  82973. }
  82974. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  82975. if (updateChildren) {
  82976. for (var index = 0; index < this.children.length; index++) {
  82977. this.children[index]._updateDifferenceMatrix();
  82978. }
  82979. }
  82980. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  82981. };
  82982. /**
  82983. * Flag the bone as dirty (Forcing it to update everything)
  82984. */
  82985. Bone.prototype.markAsDirty = function () {
  82986. this._currentRenderId++;
  82987. this._childRenderId++;
  82988. this._skeleton._markAsDirty();
  82989. };
  82990. Bone.prototype._markAsDirtyAndCompose = function () {
  82991. this.markAsDirty();
  82992. this._needToCompose = true;
  82993. };
  82994. Bone.prototype._markAsDirtyAndDecompose = function () {
  82995. this.markAsDirty();
  82996. this._needToDecompose = true;
  82997. };
  82998. /**
  82999. * Copy an animation range from another bone
  83000. * @param source defines the source bone
  83001. * @param rangeName defines the range name to copy
  83002. * @param frameOffset defines the frame offset
  83003. * @param rescaleAsRequired defines if rescaling must be applied if required
  83004. * @param skelDimensionsRatio defines the scaling ratio
  83005. * @returns true if operation was successful
  83006. */
  83007. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  83008. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  83009. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  83010. // all animation may be coming from a library skeleton, so may need to create animation
  83011. if (this.animations.length === 0) {
  83012. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  83013. this.animations[0].setKeys([]);
  83014. }
  83015. // get animation info / verify there is such a range from the source bone
  83016. var sourceRange = source.animations[0].getRange(rangeName);
  83017. if (!sourceRange) {
  83018. return false;
  83019. }
  83020. var from = sourceRange.from;
  83021. var to = sourceRange.to;
  83022. var sourceKeys = source.animations[0].getKeys();
  83023. // rescaling prep
  83024. var sourceBoneLength = source.length;
  83025. var sourceParent = source.getParent();
  83026. var parent = this.getParent();
  83027. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  83028. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  83029. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  83030. var destKeys = this.animations[0].getKeys();
  83031. // loop vars declaration
  83032. var orig;
  83033. var origTranslation;
  83034. var mat;
  83035. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  83036. orig = sourceKeys[key];
  83037. if (orig.frame >= from && orig.frame <= to) {
  83038. if (rescaleAsRequired) {
  83039. mat = orig.value.clone();
  83040. // scale based on parent ratio, when bone has parent
  83041. if (parentScalingReqd) {
  83042. origTranslation = mat.getTranslation();
  83043. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  83044. // scale based on skeleton dimension ratio when root bone, and value is passed
  83045. }
  83046. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  83047. origTranslation = mat.getTranslation();
  83048. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  83049. // use original when root bone, and no data for skelDimensionsRatio
  83050. }
  83051. else {
  83052. mat = orig.value;
  83053. }
  83054. }
  83055. else {
  83056. mat = orig.value;
  83057. }
  83058. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  83059. }
  83060. }
  83061. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  83062. return true;
  83063. };
  83064. /**
  83065. * Translate the bone in local or world space
  83066. * @param vec The amount to translate the bone
  83067. * @param space The space that the translation is in
  83068. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83069. */
  83070. Bone.prototype.translate = function (vec, space, mesh) {
  83071. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83072. var lm = this.getLocalMatrix();
  83073. if (space == BABYLON.Space.LOCAL) {
  83074. lm.m[12] += vec.x;
  83075. lm.m[13] += vec.y;
  83076. lm.m[14] += vec.z;
  83077. }
  83078. else {
  83079. var wm = null;
  83080. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83081. if (mesh) {
  83082. wm = mesh.getWorldMatrix();
  83083. }
  83084. this._skeleton.computeAbsoluteTransforms();
  83085. var tmat = Bone._tmpMats[0];
  83086. var tvec = Bone._tmpVecs[0];
  83087. if (this._parent) {
  83088. if (mesh && wm) {
  83089. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83090. tmat.multiplyToRef(wm, tmat);
  83091. }
  83092. else {
  83093. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83094. }
  83095. }
  83096. tmat.m[12] = 0;
  83097. tmat.m[13] = 0;
  83098. tmat.m[14] = 0;
  83099. tmat.invert();
  83100. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  83101. lm.m[12] += tvec.x;
  83102. lm.m[13] += tvec.y;
  83103. lm.m[14] += tvec.z;
  83104. }
  83105. this._markAsDirtyAndDecompose();
  83106. };
  83107. /**
  83108. * Set the postion of the bone in local or world space
  83109. * @param position The position to set the bone
  83110. * @param space The space that the position is in
  83111. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83112. */
  83113. Bone.prototype.setPosition = function (position, space, mesh) {
  83114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83115. var lm = this.getLocalMatrix();
  83116. if (space == BABYLON.Space.LOCAL) {
  83117. lm.m[12] = position.x;
  83118. lm.m[13] = position.y;
  83119. lm.m[14] = position.z;
  83120. }
  83121. else {
  83122. var wm = null;
  83123. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83124. if (mesh) {
  83125. wm = mesh.getWorldMatrix();
  83126. }
  83127. this._skeleton.computeAbsoluteTransforms();
  83128. var tmat = Bone._tmpMats[0];
  83129. var vec = Bone._tmpVecs[0];
  83130. if (this._parent) {
  83131. if (mesh && wm) {
  83132. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83133. tmat.multiplyToRef(wm, tmat);
  83134. }
  83135. else {
  83136. tmat.copyFrom(this._parent.getAbsoluteTransform());
  83137. }
  83138. }
  83139. tmat.invert();
  83140. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  83141. lm.m[12] = vec.x;
  83142. lm.m[13] = vec.y;
  83143. lm.m[14] = vec.z;
  83144. }
  83145. this._markAsDirtyAndDecompose();
  83146. };
  83147. /**
  83148. * Set the absolute position of the bone (world space)
  83149. * @param position The position to set the bone
  83150. * @param mesh The mesh that this bone is attached to
  83151. */
  83152. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  83153. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  83154. };
  83155. /**
  83156. * Scale the bone on the x, y and z axes (in local space)
  83157. * @param x The amount to scale the bone on the x axis
  83158. * @param y The amount to scale the bone on the y axis
  83159. * @param z The amount to scale the bone on the z axis
  83160. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  83161. */
  83162. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  83163. if (scaleChildren === void 0) { scaleChildren = false; }
  83164. var locMat = this.getLocalMatrix();
  83165. // Apply new scaling on top of current local matrix
  83166. var scaleMat = Bone._tmpMats[0];
  83167. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  83168. scaleMat.multiplyToRef(locMat, locMat);
  83169. // Invert scaling matrix and apply the inverse to all children
  83170. scaleMat.invert();
  83171. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  83172. var child = _a[_i];
  83173. var cm = child.getLocalMatrix();
  83174. cm.multiplyToRef(scaleMat, cm);
  83175. cm.m[12] *= x;
  83176. cm.m[13] *= y;
  83177. cm.m[14] *= z;
  83178. child._markAsDirtyAndDecompose();
  83179. }
  83180. this._markAsDirtyAndDecompose();
  83181. if (scaleChildren) {
  83182. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  83183. var child = _c[_b];
  83184. child.scale(x, y, z, scaleChildren);
  83185. }
  83186. }
  83187. };
  83188. /**
  83189. * Set the bone scaling in local space
  83190. * @param scale defines the scaling vector
  83191. */
  83192. Bone.prototype.setScale = function (scale) {
  83193. this._decompose();
  83194. this._localScaling.copyFrom(scale);
  83195. this._markAsDirtyAndCompose();
  83196. };
  83197. /**
  83198. * Gets the current scaling in local space
  83199. * @returns the current scaling vector
  83200. */
  83201. Bone.prototype.getScale = function () {
  83202. this._decompose();
  83203. return this._localScaling;
  83204. };
  83205. /**
  83206. * Gets the current scaling in local space and stores it in a target vector
  83207. * @param result defines the target vector
  83208. */
  83209. Bone.prototype.getScaleToRef = function (result) {
  83210. this._decompose();
  83211. result.copyFrom(this._localScaling);
  83212. };
  83213. /**
  83214. * Set the yaw, pitch, and roll of the bone in local or world space
  83215. * @param yaw The rotation of the bone on the y axis
  83216. * @param pitch The rotation of the bone on the x axis
  83217. * @param roll The rotation of the bone on the z axis
  83218. * @param space The space that the axes of rotation are in
  83219. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83220. */
  83221. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  83222. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83223. if (space === BABYLON.Space.LOCAL) {
  83224. var quat = Bone._tmpQuat;
  83225. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  83226. this.setRotationQuaternion(quat, space, mesh);
  83227. return;
  83228. }
  83229. var rotMatInv = Bone._tmpMats[0];
  83230. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83231. return;
  83232. }
  83233. var rotMat = Bone._tmpMats[1];
  83234. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  83235. rotMatInv.multiplyToRef(rotMat, rotMat);
  83236. this._rotateWithMatrix(rotMat, space, mesh);
  83237. };
  83238. /**
  83239. * Add a rotation to the bone on an axis in local or world space
  83240. * @param axis The axis to rotate the bone on
  83241. * @param amount The amount to rotate the bone
  83242. * @param space The space that the axis is in
  83243. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83244. */
  83245. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  83246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83247. var rmat = Bone._tmpMats[0];
  83248. rmat.m[12] = 0;
  83249. rmat.m[13] = 0;
  83250. rmat.m[14] = 0;
  83251. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  83252. this._rotateWithMatrix(rmat, space, mesh);
  83253. };
  83254. /**
  83255. * Set the rotation of the bone to a particular axis angle in local or world space
  83256. * @param axis The axis to rotate the bone on
  83257. * @param angle The angle that the bone should be rotated to
  83258. * @param space The space that the axis is in
  83259. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83260. */
  83261. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  83262. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83263. if (space === BABYLON.Space.LOCAL) {
  83264. var quat = Bone._tmpQuat;
  83265. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  83266. this.setRotationQuaternion(quat, space, mesh);
  83267. return;
  83268. }
  83269. var rotMatInv = Bone._tmpMats[0];
  83270. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83271. return;
  83272. }
  83273. var rotMat = Bone._tmpMats[1];
  83274. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  83275. rotMatInv.multiplyToRef(rotMat, rotMat);
  83276. this._rotateWithMatrix(rotMat, space, mesh);
  83277. };
  83278. /**
  83279. * Set the euler rotation of the bone in local of world space
  83280. * @param rotation The euler rotation that the bone should be set to
  83281. * @param space The space that the rotation is in
  83282. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83283. */
  83284. Bone.prototype.setRotation = function (rotation, space, mesh) {
  83285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83286. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  83287. };
  83288. /**
  83289. * Set the quaternion rotation of the bone in local of world space
  83290. * @param quat The quaternion rotation that the bone should be set to
  83291. * @param space The space that the rotation is in
  83292. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83293. */
  83294. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  83295. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83296. if (space === BABYLON.Space.LOCAL) {
  83297. this._decompose();
  83298. this._localRotation.copyFrom(quat);
  83299. this._markAsDirtyAndCompose();
  83300. return;
  83301. }
  83302. var rotMatInv = Bone._tmpMats[0];
  83303. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83304. return;
  83305. }
  83306. var rotMat = Bone._tmpMats[1];
  83307. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  83308. rotMatInv.multiplyToRef(rotMat, rotMat);
  83309. this._rotateWithMatrix(rotMat, space, mesh);
  83310. };
  83311. /**
  83312. * Set the rotation matrix of the bone in local of world space
  83313. * @param rotMat The rotation matrix that the bone should be set to
  83314. * @param space The space that the rotation is in
  83315. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83316. */
  83317. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  83318. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83319. if (space === BABYLON.Space.LOCAL) {
  83320. var quat = Bone._tmpQuat;
  83321. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  83322. this.setRotationQuaternion(quat, space, mesh);
  83323. return;
  83324. }
  83325. var rotMatInv = Bone._tmpMats[0];
  83326. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  83327. return;
  83328. }
  83329. var rotMat2 = Bone._tmpMats[1];
  83330. rotMat2.copyFrom(rotMat);
  83331. rotMatInv.multiplyToRef(rotMat, rotMat2);
  83332. this._rotateWithMatrix(rotMat2, space, mesh);
  83333. };
  83334. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  83335. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83336. var lmat = this.getLocalMatrix();
  83337. var lx = lmat.m[12];
  83338. var ly = lmat.m[13];
  83339. var lz = lmat.m[14];
  83340. var parent = this.getParent();
  83341. var parentScale = Bone._tmpMats[3];
  83342. var parentScaleInv = Bone._tmpMats[4];
  83343. if (parent && space == BABYLON.Space.WORLD) {
  83344. if (mesh) {
  83345. parentScale.copyFrom(mesh.getWorldMatrix());
  83346. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  83347. }
  83348. else {
  83349. parentScale.copyFrom(parent.getAbsoluteTransform());
  83350. }
  83351. parentScaleInv.copyFrom(parentScale);
  83352. parentScaleInv.invert();
  83353. lmat.multiplyToRef(parentScale, lmat);
  83354. lmat.multiplyToRef(rmat, lmat);
  83355. lmat.multiplyToRef(parentScaleInv, lmat);
  83356. }
  83357. else {
  83358. if (space == BABYLON.Space.WORLD && mesh) {
  83359. parentScale.copyFrom(mesh.getWorldMatrix());
  83360. parentScaleInv.copyFrom(parentScale);
  83361. parentScaleInv.invert();
  83362. lmat.multiplyToRef(parentScale, lmat);
  83363. lmat.multiplyToRef(rmat, lmat);
  83364. lmat.multiplyToRef(parentScaleInv, lmat);
  83365. }
  83366. else {
  83367. lmat.multiplyToRef(rmat, lmat);
  83368. }
  83369. }
  83370. lmat.m[12] = lx;
  83371. lmat.m[13] = ly;
  83372. lmat.m[14] = lz;
  83373. this.computeAbsoluteTransforms();
  83374. this._markAsDirtyAndDecompose();
  83375. };
  83376. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  83377. var scaleMatrix = Bone._tmpMats[2];
  83378. rotMatInv.copyFrom(this.getAbsoluteTransform());
  83379. if (mesh) {
  83380. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  83381. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  83382. }
  83383. rotMatInv.invert();
  83384. if (isNaN(rotMatInv.m[0])) {
  83385. // Matrix failed to invert.
  83386. // This can happen if scale is zero for example.
  83387. return false;
  83388. }
  83389. scaleMatrix.m[0] *= this._scalingDeterminant;
  83390. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  83391. return true;
  83392. };
  83393. /**
  83394. * Get the position of the bone in local or world space
  83395. * @param space The space that the returned position is in
  83396. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83397. * @returns The position of the bone
  83398. */
  83399. Bone.prototype.getPosition = function (space, mesh) {
  83400. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83401. if (mesh === void 0) { mesh = null; }
  83402. var pos = BABYLON.Vector3.Zero();
  83403. this.getPositionToRef(space, mesh, pos);
  83404. return pos;
  83405. };
  83406. /**
  83407. * Copy the position of the bone to a vector3 in local or world space
  83408. * @param space The space that the returned position is in
  83409. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83410. * @param result The vector3 to copy the position to
  83411. */
  83412. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  83413. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83414. if (space == BABYLON.Space.LOCAL) {
  83415. var lm = this.getLocalMatrix();
  83416. result.x = lm.m[12];
  83417. result.y = lm.m[13];
  83418. result.z = lm.m[14];
  83419. }
  83420. else {
  83421. var wm = null;
  83422. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83423. if (mesh) {
  83424. wm = mesh.getWorldMatrix();
  83425. }
  83426. this._skeleton.computeAbsoluteTransforms();
  83427. var tmat = Bone._tmpMats[0];
  83428. if (mesh && wm) {
  83429. tmat.copyFrom(this.getAbsoluteTransform());
  83430. tmat.multiplyToRef(wm, tmat);
  83431. }
  83432. else {
  83433. tmat = this.getAbsoluteTransform();
  83434. }
  83435. result.x = tmat.m[12];
  83436. result.y = tmat.m[13];
  83437. result.z = tmat.m[14];
  83438. }
  83439. };
  83440. /**
  83441. * Get the absolute position of the bone (world space)
  83442. * @param mesh The mesh that this bone is attached to
  83443. * @returns The absolute position of the bone
  83444. */
  83445. Bone.prototype.getAbsolutePosition = function (mesh) {
  83446. if (mesh === void 0) { mesh = null; }
  83447. var pos = BABYLON.Vector3.Zero();
  83448. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  83449. return pos;
  83450. };
  83451. /**
  83452. * Copy the absolute position of the bone (world space) to the result param
  83453. * @param mesh The mesh that this bone is attached to
  83454. * @param result The vector3 to copy the absolute position to
  83455. */
  83456. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  83457. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  83458. };
  83459. /**
  83460. * Compute the absolute transforms of this bone and its children
  83461. */
  83462. Bone.prototype.computeAbsoluteTransforms = function () {
  83463. this._compose();
  83464. if (this._parent) {
  83465. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  83466. }
  83467. else {
  83468. this._absoluteTransform.copyFrom(this._localMatrix);
  83469. var poseMatrix = this._skeleton.getPoseMatrix();
  83470. if (poseMatrix) {
  83471. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  83472. }
  83473. }
  83474. var children = this.children;
  83475. var len = children.length;
  83476. for (var i = 0; i < len; i++) {
  83477. children[i].computeAbsoluteTransforms();
  83478. }
  83479. };
  83480. /**
  83481. * Get the world direction from an axis that is in the local space of the bone
  83482. * @param localAxis The local direction that is used to compute the world direction
  83483. * @param mesh The mesh that this bone is attached to
  83484. * @returns The world direction
  83485. */
  83486. Bone.prototype.getDirection = function (localAxis, mesh) {
  83487. if (mesh === void 0) { mesh = null; }
  83488. var result = BABYLON.Vector3.Zero();
  83489. this.getDirectionToRef(localAxis, mesh, result);
  83490. return result;
  83491. };
  83492. /**
  83493. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  83494. * @param localAxis The local direction that is used to compute the world direction
  83495. * @param mesh The mesh that this bone is attached to
  83496. * @param result The vector3 that the world direction will be copied to
  83497. */
  83498. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  83499. if (mesh === void 0) { mesh = null; }
  83500. var wm = null;
  83501. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83502. if (mesh) {
  83503. wm = mesh.getWorldMatrix();
  83504. }
  83505. this._skeleton.computeAbsoluteTransforms();
  83506. var mat = Bone._tmpMats[0];
  83507. mat.copyFrom(this.getAbsoluteTransform());
  83508. if (mesh && wm) {
  83509. mat.multiplyToRef(wm, mat);
  83510. }
  83511. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  83512. result.normalize();
  83513. };
  83514. /**
  83515. * Get the euler rotation of the bone in local or world space
  83516. * @param space The space that the rotation should be in
  83517. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83518. * @returns The euler rotation
  83519. */
  83520. Bone.prototype.getRotation = function (space, mesh) {
  83521. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83522. if (mesh === void 0) { mesh = null; }
  83523. var result = BABYLON.Vector3.Zero();
  83524. this.getRotationToRef(space, mesh, result);
  83525. return result;
  83526. };
  83527. /**
  83528. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  83529. * @param space The space that the rotation should be in
  83530. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83531. * @param result The vector3 that the rotation should be copied to
  83532. */
  83533. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  83534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83535. if (mesh === void 0) { mesh = null; }
  83536. var quat = Bone._tmpQuat;
  83537. this.getRotationQuaternionToRef(space, mesh, quat);
  83538. quat.toEulerAnglesToRef(result);
  83539. };
  83540. /**
  83541. * Get the quaternion rotation of the bone in either local or world space
  83542. * @param space The space that the rotation should be in
  83543. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83544. * @returns The quaternion rotation
  83545. */
  83546. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  83547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83548. if (mesh === void 0) { mesh = null; }
  83549. var result = BABYLON.Quaternion.Identity();
  83550. this.getRotationQuaternionToRef(space, mesh, result);
  83551. return result;
  83552. };
  83553. /**
  83554. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  83555. * @param space The space that the rotation should be in
  83556. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83557. * @param result The quaternion that the rotation should be copied to
  83558. */
  83559. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  83560. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83561. if (mesh === void 0) { mesh = null; }
  83562. if (space == BABYLON.Space.LOCAL) {
  83563. this._decompose();
  83564. result.copyFrom(this._localRotation);
  83565. }
  83566. else {
  83567. var mat = Bone._tmpMats[0];
  83568. var amat = this.getAbsoluteTransform();
  83569. if (mesh) {
  83570. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83571. }
  83572. else {
  83573. mat.copyFrom(amat);
  83574. }
  83575. mat.m[0] *= this._scalingDeterminant;
  83576. mat.m[1] *= this._scalingDeterminant;
  83577. mat.m[2] *= this._scalingDeterminant;
  83578. mat.decompose(undefined, result, undefined);
  83579. }
  83580. };
  83581. /**
  83582. * Get the rotation matrix of the bone in local or world space
  83583. * @param space The space that the rotation should be in
  83584. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83585. * @returns The rotation matrix
  83586. */
  83587. Bone.prototype.getRotationMatrix = function (space, mesh) {
  83588. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83589. var result = BABYLON.Matrix.Identity();
  83590. this.getRotationMatrixToRef(space, mesh, result);
  83591. return result;
  83592. };
  83593. /**
  83594. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  83595. * @param space The space that the rotation should be in
  83596. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83597. * @param result The quaternion that the rotation should be copied to
  83598. */
  83599. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  83600. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83601. if (space == BABYLON.Space.LOCAL) {
  83602. this.getLocalMatrix().getRotationMatrixToRef(result);
  83603. }
  83604. else {
  83605. var mat = Bone._tmpMats[0];
  83606. var amat = this.getAbsoluteTransform();
  83607. if (mesh) {
  83608. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83609. }
  83610. else {
  83611. mat.copyFrom(amat);
  83612. }
  83613. mat.m[0] *= this._scalingDeterminant;
  83614. mat.m[1] *= this._scalingDeterminant;
  83615. mat.m[2] *= this._scalingDeterminant;
  83616. mat.getRotationMatrixToRef(result);
  83617. }
  83618. };
  83619. /**
  83620. * Get the world position of a point that is in the local space of the bone
  83621. * @param position The local position
  83622. * @param mesh The mesh that this bone is attached to
  83623. * @returns The world position
  83624. */
  83625. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  83626. if (mesh === void 0) { mesh = null; }
  83627. var result = BABYLON.Vector3.Zero();
  83628. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  83629. return result;
  83630. };
  83631. /**
  83632. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  83633. * @param position The local position
  83634. * @param mesh The mesh that this bone is attached to
  83635. * @param result The vector3 that the world position should be copied to
  83636. */
  83637. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  83638. if (mesh === void 0) { mesh = null; }
  83639. var wm = null;
  83640. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83641. if (mesh) {
  83642. wm = mesh.getWorldMatrix();
  83643. }
  83644. this._skeleton.computeAbsoluteTransforms();
  83645. var tmat = Bone._tmpMats[0];
  83646. if (mesh && wm) {
  83647. tmat.copyFrom(this.getAbsoluteTransform());
  83648. tmat.multiplyToRef(wm, tmat);
  83649. }
  83650. else {
  83651. tmat = this.getAbsoluteTransform();
  83652. }
  83653. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83654. };
  83655. /**
  83656. * Get the local position of a point that is in world space
  83657. * @param position The world position
  83658. * @param mesh The mesh that this bone is attached to
  83659. * @returns The local position
  83660. */
  83661. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  83662. if (mesh === void 0) { mesh = null; }
  83663. var result = BABYLON.Vector3.Zero();
  83664. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  83665. return result;
  83666. };
  83667. /**
  83668. * Get the local position of a point that is in world space and copy it to the result param
  83669. * @param position The world position
  83670. * @param mesh The mesh that this bone is attached to
  83671. * @param result The vector3 that the local position should be copied to
  83672. */
  83673. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  83674. if (mesh === void 0) { mesh = null; }
  83675. var wm = null;
  83676. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83677. if (mesh) {
  83678. wm = mesh.getWorldMatrix();
  83679. }
  83680. this._skeleton.computeAbsoluteTransforms();
  83681. var tmat = Bone._tmpMats[0];
  83682. tmat.copyFrom(this.getAbsoluteTransform());
  83683. if (mesh && wm) {
  83684. tmat.multiplyToRef(wm, tmat);
  83685. }
  83686. tmat.invert();
  83687. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83688. };
  83689. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83690. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  83691. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83692. return Bone;
  83693. }(BABYLON.Node));
  83694. BABYLON.Bone = Bone;
  83695. })(BABYLON || (BABYLON = {}));
  83696. //# sourceMappingURL=babylon.bone.js.map
  83697. var BABYLON;
  83698. (function (BABYLON) {
  83699. /**
  83700. * Class used to apply inverse kinematics to bones
  83701. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  83702. */
  83703. var BoneIKController = /** @class */ (function () {
  83704. /**
  83705. * Creates a new BoneIKController
  83706. * @param mesh defines the mesh to control
  83707. * @param bone defines the bone to control
  83708. * @param options defines options to set up the controller
  83709. */
  83710. function BoneIKController(mesh, bone, options) {
  83711. /**
  83712. * Gets or sets the target position
  83713. */
  83714. this.targetPosition = BABYLON.Vector3.Zero();
  83715. /**
  83716. * Gets or sets the pole target position
  83717. */
  83718. this.poleTargetPosition = BABYLON.Vector3.Zero();
  83719. /**
  83720. * Gets or sets the pole target local offset
  83721. */
  83722. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  83723. /**
  83724. * Gets or sets the pole angle
  83725. */
  83726. this.poleAngle = 0;
  83727. /**
  83728. * 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)
  83729. */
  83730. this.slerpAmount = 1;
  83731. this._bone1Quat = BABYLON.Quaternion.Identity();
  83732. this._bone1Mat = BABYLON.Matrix.Identity();
  83733. this._bone2Ang = Math.PI;
  83734. this._maxAngle = Math.PI;
  83735. this._rightHandedSystem = false;
  83736. this._bendAxis = BABYLON.Vector3.Right();
  83737. this._slerping = false;
  83738. this._adjustRoll = 0;
  83739. this._bone2 = bone;
  83740. this._bone1 = bone.getParent();
  83741. if (!this._bone1) {
  83742. return;
  83743. }
  83744. this.mesh = mesh;
  83745. var bonePos = bone.getPosition();
  83746. if (bone.getAbsoluteTransform().determinant() > 0) {
  83747. this._rightHandedSystem = true;
  83748. this._bendAxis.x = 0;
  83749. this._bendAxis.y = 0;
  83750. this._bendAxis.z = -1;
  83751. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  83752. this._adjustRoll = Math.PI * .5;
  83753. this._bendAxis.z = 1;
  83754. }
  83755. }
  83756. if (this._bone1.length) {
  83757. var boneScale1 = this._bone1.getScale();
  83758. var boneScale2 = this._bone2.getScale();
  83759. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  83760. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  83761. }
  83762. else if (this._bone1.children[0]) {
  83763. mesh.computeWorldMatrix(true);
  83764. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  83765. var pos2 = this._bone2.getAbsolutePosition(mesh);
  83766. var pos3 = this._bone1.getAbsolutePosition(mesh);
  83767. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  83768. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  83769. }
  83770. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  83771. this.maxAngle = Math.PI;
  83772. if (options) {
  83773. if (options.targetMesh) {
  83774. this.targetMesh = options.targetMesh;
  83775. this.targetMesh.computeWorldMatrix(true);
  83776. }
  83777. if (options.poleTargetMesh) {
  83778. this.poleTargetMesh = options.poleTargetMesh;
  83779. this.poleTargetMesh.computeWorldMatrix(true);
  83780. }
  83781. else if (options.poleTargetBone) {
  83782. this.poleTargetBone = options.poleTargetBone;
  83783. }
  83784. else if (this._bone1.getParent()) {
  83785. this.poleTargetBone = this._bone1.getParent();
  83786. }
  83787. if (options.poleTargetLocalOffset) {
  83788. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  83789. }
  83790. if (options.poleAngle) {
  83791. this.poleAngle = options.poleAngle;
  83792. }
  83793. if (options.bendAxis) {
  83794. this._bendAxis.copyFrom(options.bendAxis);
  83795. }
  83796. if (options.maxAngle) {
  83797. this.maxAngle = options.maxAngle;
  83798. }
  83799. if (options.slerpAmount) {
  83800. this.slerpAmount = options.slerpAmount;
  83801. }
  83802. }
  83803. }
  83804. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  83805. /**
  83806. * Gets or sets maximum allowed angle
  83807. */
  83808. get: function () {
  83809. return this._maxAngle;
  83810. },
  83811. set: function (value) {
  83812. this._setMaxAngle(value);
  83813. },
  83814. enumerable: true,
  83815. configurable: true
  83816. });
  83817. BoneIKController.prototype._setMaxAngle = function (ang) {
  83818. if (ang < 0) {
  83819. ang = 0;
  83820. }
  83821. if (ang > Math.PI || ang == undefined) {
  83822. ang = Math.PI;
  83823. }
  83824. this._maxAngle = ang;
  83825. var a = this._bone1Length;
  83826. var b = this._bone2Length;
  83827. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  83828. };
  83829. /**
  83830. * Force the controller to update the bones
  83831. */
  83832. BoneIKController.prototype.update = function () {
  83833. var bone1 = this._bone1;
  83834. if (!bone1) {
  83835. return;
  83836. }
  83837. var target = this.targetPosition;
  83838. var poleTarget = this.poleTargetPosition;
  83839. var mat1 = BoneIKController._tmpMats[0];
  83840. var mat2 = BoneIKController._tmpMats[1];
  83841. if (this.targetMesh) {
  83842. target.copyFrom(this.targetMesh.getAbsolutePosition());
  83843. }
  83844. if (this.poleTargetBone) {
  83845. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  83846. }
  83847. else if (this.poleTargetMesh) {
  83848. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  83849. }
  83850. var bonePos = BoneIKController._tmpVecs[0];
  83851. var zaxis = BoneIKController._tmpVecs[1];
  83852. var xaxis = BoneIKController._tmpVecs[2];
  83853. var yaxis = BoneIKController._tmpVecs[3];
  83854. var upAxis = BoneIKController._tmpVecs[4];
  83855. var _tmpQuat = BoneIKController._tmpQuat;
  83856. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  83857. poleTarget.subtractToRef(bonePos, upAxis);
  83858. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  83859. upAxis.y = 1;
  83860. }
  83861. else {
  83862. upAxis.normalize();
  83863. }
  83864. target.subtractToRef(bonePos, yaxis);
  83865. yaxis.normalize();
  83866. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  83867. zaxis.normalize();
  83868. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  83869. xaxis.normalize();
  83870. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  83871. var a = this._bone1Length;
  83872. var b = this._bone2Length;
  83873. var c = BABYLON.Vector3.Distance(bonePos, target);
  83874. if (this._maxReach > 0) {
  83875. c = Math.min(this._maxReach, c);
  83876. }
  83877. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  83878. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  83879. if (acosa > 1) {
  83880. acosa = 1;
  83881. }
  83882. if (acosb > 1) {
  83883. acosb = 1;
  83884. }
  83885. if (acosa < -1) {
  83886. acosa = -1;
  83887. }
  83888. if (acosb < -1) {
  83889. acosb = -1;
  83890. }
  83891. var angA = Math.acos(acosa);
  83892. var angB = Math.acos(acosb);
  83893. var angC = -angA - angB;
  83894. if (this._rightHandedSystem) {
  83895. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  83896. mat2.multiplyToRef(mat1, mat1);
  83897. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  83898. mat2.multiplyToRef(mat1, mat1);
  83899. }
  83900. else {
  83901. var _tmpVec = BoneIKController._tmpVecs[5];
  83902. _tmpVec.copyFrom(this._bendAxis);
  83903. _tmpVec.x *= -1;
  83904. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  83905. mat2.multiplyToRef(mat1, mat1);
  83906. }
  83907. if (this.poleAngle) {
  83908. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  83909. mat1.multiplyToRef(mat2, mat1);
  83910. }
  83911. if (this._bone1) {
  83912. if (this.slerpAmount < 1) {
  83913. if (!this._slerping) {
  83914. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  83915. }
  83916. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  83917. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  83918. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  83919. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  83920. this._slerping = true;
  83921. }
  83922. else {
  83923. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  83924. this._bone1Mat.copyFrom(mat1);
  83925. this._slerping = false;
  83926. }
  83927. }
  83928. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  83929. this._bone2Ang = angC;
  83930. };
  83931. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83932. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  83933. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83934. return BoneIKController;
  83935. }());
  83936. BABYLON.BoneIKController = BoneIKController;
  83937. })(BABYLON || (BABYLON = {}));
  83938. //# sourceMappingURL=babylon.boneIKController.js.map
  83939. var BABYLON;
  83940. (function (BABYLON) {
  83941. /**
  83942. * Class used to make a bone look toward a point in space
  83943. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  83944. */
  83945. var BoneLookController = /** @class */ (function () {
  83946. /**
  83947. * Create a BoneLookController
  83948. * @param mesh the mesh that the bone belongs to
  83949. * @param bone the bone that will be looking to the target
  83950. * @param target the target Vector3 to look at
  83951. * @param settings optional settings:
  83952. * * maxYaw: the maximum angle the bone will yaw to
  83953. * * minYaw: the minimum angle the bone will yaw to
  83954. * * maxPitch: the maximum angle the bone will pitch to
  83955. * * minPitch: the minimum angle the bone will yaw to
  83956. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  83957. * * upAxis: the up axis of the coordinate system
  83958. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  83959. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  83960. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  83961. * * adjustYaw: used to make an adjustment to the yaw of the bone
  83962. * * adjustPitch: used to make an adjustment to the pitch of the bone
  83963. * * adjustRoll: used to make an adjustment to the roll of the bone
  83964. **/
  83965. function BoneLookController(mesh, bone, target, options) {
  83966. /**
  83967. * The up axis of the coordinate system that is used when the bone is rotated
  83968. */
  83969. this.upAxis = BABYLON.Vector3.Up();
  83970. /**
  83971. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  83972. */
  83973. this.upAxisSpace = BABYLON.Space.LOCAL;
  83974. /**
  83975. * Used to make an adjustment to the yaw of the bone
  83976. */
  83977. this.adjustYaw = 0;
  83978. /**
  83979. * Used to make an adjustment to the pitch of the bone
  83980. */
  83981. this.adjustPitch = 0;
  83982. /**
  83983. * Used to make an adjustment to the roll of the bone
  83984. */
  83985. this.adjustRoll = 0;
  83986. /**
  83987. * 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)
  83988. */
  83989. this.slerpAmount = 1;
  83990. this._boneQuat = BABYLON.Quaternion.Identity();
  83991. this._slerping = false;
  83992. this._firstFrameSkipped = false;
  83993. this._fowardAxis = BABYLON.Vector3.Forward();
  83994. this.mesh = mesh;
  83995. this.bone = bone;
  83996. this.target = target;
  83997. if (options) {
  83998. if (options.adjustYaw) {
  83999. this.adjustYaw = options.adjustYaw;
  84000. }
  84001. if (options.adjustPitch) {
  84002. this.adjustPitch = options.adjustPitch;
  84003. }
  84004. if (options.adjustRoll) {
  84005. this.adjustRoll = options.adjustRoll;
  84006. }
  84007. if (options.maxYaw != null) {
  84008. this.maxYaw = options.maxYaw;
  84009. }
  84010. else {
  84011. this.maxYaw = Math.PI;
  84012. }
  84013. if (options.minYaw != null) {
  84014. this.minYaw = options.minYaw;
  84015. }
  84016. else {
  84017. this.minYaw = -Math.PI;
  84018. }
  84019. if (options.maxPitch != null) {
  84020. this.maxPitch = options.maxPitch;
  84021. }
  84022. else {
  84023. this.maxPitch = Math.PI;
  84024. }
  84025. if (options.minPitch != null) {
  84026. this.minPitch = options.minPitch;
  84027. }
  84028. else {
  84029. this.minPitch = -Math.PI;
  84030. }
  84031. if (options.slerpAmount != null) {
  84032. this.slerpAmount = options.slerpAmount;
  84033. }
  84034. if (options.upAxis != null) {
  84035. this.upAxis = options.upAxis;
  84036. }
  84037. if (options.upAxisSpace != null) {
  84038. this.upAxisSpace = options.upAxisSpace;
  84039. }
  84040. if (options.yawAxis != null || options.pitchAxis != null) {
  84041. var newYawAxis = BABYLON.Axis.Y;
  84042. var newPitchAxis = BABYLON.Axis.X;
  84043. if (options.yawAxis != null) {
  84044. newYawAxis = options.yawAxis.clone();
  84045. newYawAxis.normalize();
  84046. }
  84047. if (options.pitchAxis != null) {
  84048. newPitchAxis = options.pitchAxis.clone();
  84049. newPitchAxis.normalize();
  84050. }
  84051. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  84052. this._transformYawPitch = BABYLON.Matrix.Identity();
  84053. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  84054. this._transformYawPitchInv = this._transformYawPitch.clone();
  84055. this._transformYawPitch.invert();
  84056. }
  84057. }
  84058. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  84059. this.upAxisSpace = BABYLON.Space.LOCAL;
  84060. }
  84061. }
  84062. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  84063. /**
  84064. * Gets or sets the minimum yaw angle that the bone can look to
  84065. */
  84066. get: function () {
  84067. return this._minYaw;
  84068. },
  84069. set: function (value) {
  84070. this._minYaw = value;
  84071. this._minYawSin = Math.sin(value);
  84072. this._minYawCos = Math.cos(value);
  84073. if (this._maxYaw != null) {
  84074. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84075. this._yawRange = this._maxYaw - this._minYaw;
  84076. }
  84077. },
  84078. enumerable: true,
  84079. configurable: true
  84080. });
  84081. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  84082. /**
  84083. * Gets or sets the maximum yaw angle that the bone can look to
  84084. */
  84085. get: function () {
  84086. return this._maxYaw;
  84087. },
  84088. set: function (value) {
  84089. this._maxYaw = value;
  84090. this._maxYawSin = Math.sin(value);
  84091. this._maxYawCos = Math.cos(value);
  84092. if (this._minYaw != null) {
  84093. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  84094. this._yawRange = this._maxYaw - this._minYaw;
  84095. }
  84096. },
  84097. enumerable: true,
  84098. configurable: true
  84099. });
  84100. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  84101. /**
  84102. * Gets or sets the minimum pitch angle that the bone can look to
  84103. */
  84104. get: function () {
  84105. return this._minPitch;
  84106. },
  84107. set: function (value) {
  84108. this._minPitch = value;
  84109. this._minPitchTan = Math.tan(value);
  84110. },
  84111. enumerable: true,
  84112. configurable: true
  84113. });
  84114. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  84115. /**
  84116. * Gets or sets the maximum pitch angle that the bone can look to
  84117. */
  84118. get: function () {
  84119. return this._maxPitch;
  84120. },
  84121. set: function (value) {
  84122. this._maxPitch = value;
  84123. this._maxPitchTan = Math.tan(value);
  84124. },
  84125. enumerable: true,
  84126. configurable: true
  84127. });
  84128. /**
  84129. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  84130. */
  84131. BoneLookController.prototype.update = function () {
  84132. //skip the first frame when slerping so that the mesh rotation is correct
  84133. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  84134. this._firstFrameSkipped = true;
  84135. return;
  84136. }
  84137. var bone = this.bone;
  84138. var bonePos = BoneLookController._tmpVecs[0];
  84139. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  84140. var target = this.target;
  84141. var _tmpMat1 = BoneLookController._tmpMats[0];
  84142. var _tmpMat2 = BoneLookController._tmpMats[1];
  84143. var mesh = this.mesh;
  84144. var parentBone = bone.getParent();
  84145. var upAxis = BoneLookController._tmpVecs[1];
  84146. upAxis.copyFrom(this.upAxis);
  84147. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  84148. if (this._transformYawPitch) {
  84149. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  84150. }
  84151. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  84152. }
  84153. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  84154. mesh.getDirectionToRef(upAxis, upAxis);
  84155. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  84156. upAxis.normalize();
  84157. }
  84158. }
  84159. var checkYaw = false;
  84160. var checkPitch = false;
  84161. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  84162. checkYaw = true;
  84163. }
  84164. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  84165. checkPitch = true;
  84166. }
  84167. if (checkYaw || checkPitch) {
  84168. var spaceMat = BoneLookController._tmpMats[2];
  84169. var spaceMatInv = BoneLookController._tmpMats[3];
  84170. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  84171. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  84172. }
  84173. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  84174. spaceMat.copyFrom(mesh.getWorldMatrix());
  84175. }
  84176. else {
  84177. var forwardAxis = BoneLookController._tmpVecs[2];
  84178. forwardAxis.copyFrom(this._fowardAxis);
  84179. if (this._transformYawPitch) {
  84180. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  84181. }
  84182. if (parentBone) {
  84183. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  84184. }
  84185. else {
  84186. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  84187. }
  84188. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  84189. rightAxis.normalize();
  84190. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  84191. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  84192. }
  84193. spaceMat.invertToRef(spaceMatInv);
  84194. var xzlen = null;
  84195. if (checkPitch) {
  84196. var localTarget = BoneLookController._tmpVecs[3];
  84197. target.subtractToRef(bonePos, localTarget);
  84198. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84199. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84200. var pitch = Math.atan2(localTarget.y, xzlen);
  84201. var newPitch = pitch;
  84202. if (pitch > this._maxPitch) {
  84203. localTarget.y = this._maxPitchTan * xzlen;
  84204. newPitch = this._maxPitch;
  84205. }
  84206. else if (pitch < this._minPitch) {
  84207. localTarget.y = this._minPitchTan * xzlen;
  84208. newPitch = this._minPitch;
  84209. }
  84210. if (pitch != newPitch) {
  84211. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84212. localTarget.addInPlace(bonePos);
  84213. target = localTarget;
  84214. }
  84215. }
  84216. if (checkYaw) {
  84217. var localTarget = BoneLookController._tmpVecs[4];
  84218. target.subtractToRef(bonePos, localTarget);
  84219. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  84220. var yaw = Math.atan2(localTarget.x, localTarget.z);
  84221. var newYaw = yaw;
  84222. if (yaw > this._maxYaw || yaw < this._minYaw) {
  84223. if (xzlen == null) {
  84224. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84225. }
  84226. if (this._yawRange > Math.PI) {
  84227. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  84228. localTarget.z = this._maxYawCos * xzlen;
  84229. localTarget.x = this._maxYawSin * xzlen;
  84230. newYaw = this._maxYaw;
  84231. }
  84232. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  84233. localTarget.z = this._minYawCos * xzlen;
  84234. localTarget.x = this._minYawSin * xzlen;
  84235. newYaw = this._minYaw;
  84236. }
  84237. }
  84238. else {
  84239. if (yaw > this._maxYaw) {
  84240. localTarget.z = this._maxYawCos * xzlen;
  84241. localTarget.x = this._maxYawSin * xzlen;
  84242. newYaw = this._maxYaw;
  84243. }
  84244. else if (yaw < this._minYaw) {
  84245. localTarget.z = this._minYawCos * xzlen;
  84246. localTarget.x = this._minYawSin * xzlen;
  84247. newYaw = this._minYaw;
  84248. }
  84249. }
  84250. }
  84251. if (this._slerping && this._yawRange > Math.PI) {
  84252. //are we going to be crossing into the min/max region?
  84253. var boneFwd = BoneLookController._tmpVecs[8];
  84254. boneFwd.copyFrom(BABYLON.Axis.Z);
  84255. if (this._transformYawPitch) {
  84256. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  84257. }
  84258. var boneRotMat = BoneLookController._tmpMats[4];
  84259. this._boneQuat.toRotationMatrix(boneRotMat);
  84260. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  84261. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  84262. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  84263. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  84264. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  84265. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  84266. if (angBtwTar > angBtwMidYaw) {
  84267. if (xzlen == null) {
  84268. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  84269. }
  84270. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  84271. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  84272. if (angBtwMin < angBtwMax) {
  84273. newYaw = boneYaw + Math.PI * .75;
  84274. localTarget.z = Math.cos(newYaw) * xzlen;
  84275. localTarget.x = Math.sin(newYaw) * xzlen;
  84276. }
  84277. else {
  84278. newYaw = boneYaw - Math.PI * .75;
  84279. localTarget.z = Math.cos(newYaw) * xzlen;
  84280. localTarget.x = Math.sin(newYaw) * xzlen;
  84281. }
  84282. }
  84283. }
  84284. if (yaw != newYaw) {
  84285. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  84286. localTarget.addInPlace(bonePos);
  84287. target = localTarget;
  84288. }
  84289. }
  84290. }
  84291. var zaxis = BoneLookController._tmpVecs[5];
  84292. var xaxis = BoneLookController._tmpVecs[6];
  84293. var yaxis = BoneLookController._tmpVecs[7];
  84294. var _tmpQuat = BoneLookController._tmpQuat;
  84295. target.subtractToRef(bonePos, zaxis);
  84296. zaxis.normalize();
  84297. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  84298. xaxis.normalize();
  84299. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  84300. yaxis.normalize();
  84301. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  84302. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  84303. return;
  84304. }
  84305. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  84306. return;
  84307. }
  84308. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  84309. return;
  84310. }
  84311. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  84312. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  84313. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  84314. }
  84315. if (this.slerpAmount < 1) {
  84316. if (!this._slerping) {
  84317. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  84318. }
  84319. if (this._transformYawPitch) {
  84320. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84321. }
  84322. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  84323. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  84324. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  84325. this._slerping = true;
  84326. }
  84327. else {
  84328. if (this._transformYawPitch) {
  84329. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  84330. }
  84331. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  84332. this._slerping = false;
  84333. }
  84334. };
  84335. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  84336. var angDiff = ang2 - ang1;
  84337. angDiff %= Math.PI * 2;
  84338. if (angDiff > Math.PI) {
  84339. angDiff -= Math.PI * 2;
  84340. }
  84341. else if (angDiff < -Math.PI) {
  84342. angDiff += Math.PI * 2;
  84343. }
  84344. return angDiff;
  84345. };
  84346. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  84347. ang1 %= (2 * Math.PI);
  84348. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84349. ang2 %= (2 * Math.PI);
  84350. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84351. var ab = 0;
  84352. if (ang1 < ang2) {
  84353. ab = ang2 - ang1;
  84354. }
  84355. else {
  84356. ab = ang1 - ang2;
  84357. }
  84358. if (ab > Math.PI) {
  84359. ab = Math.PI * 2 - ab;
  84360. }
  84361. return ab;
  84362. };
  84363. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  84364. ang %= (2 * Math.PI);
  84365. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  84366. ang1 %= (2 * Math.PI);
  84367. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  84368. ang2 %= (2 * Math.PI);
  84369. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  84370. if (ang1 < ang2) {
  84371. if (ang > ang1 && ang < ang2) {
  84372. return true;
  84373. }
  84374. }
  84375. else {
  84376. if (ang > ang2 && ang < ang1) {
  84377. return true;
  84378. }
  84379. }
  84380. return false;
  84381. };
  84382. 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()];
  84383. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  84384. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84385. return BoneLookController;
  84386. }());
  84387. BABYLON.BoneLookController = BoneLookController;
  84388. })(BABYLON || (BABYLON = {}));
  84389. //# sourceMappingURL=babylon.boneLookController.js.map
  84390. var BABYLON;
  84391. (function (BABYLON) {
  84392. /**
  84393. * Class used to handle skinning animations
  84394. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  84395. */
  84396. var Skeleton = /** @class */ (function () {
  84397. /**
  84398. * Creates a new skeleton
  84399. * @param name defines the skeleton name
  84400. * @param id defines the skeleton Id
  84401. * @param scene defines the hosting scene
  84402. */
  84403. function Skeleton(
  84404. /** defines the skeleton name */
  84405. name,
  84406. /** defines the skeleton Id */
  84407. id, scene) {
  84408. this.name = name;
  84409. this.id = id;
  84410. /**
  84411. * Gets the list of child bones
  84412. */
  84413. this.bones = new Array();
  84414. /**
  84415. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  84416. */
  84417. this.needInitialSkinMatrix = false;
  84418. this._isDirty = true;
  84419. this._meshesWithPoseMatrix = new Array();
  84420. this._identity = BABYLON.Matrix.Identity();
  84421. this._ranges = {};
  84422. this._lastAbsoluteTransformsUpdateId = -1;
  84423. /**
  84424. * Specifies if the skeleton should be serialized
  84425. */
  84426. this.doNotSerialize = false;
  84427. this._animationPropertiesOverride = null;
  84428. // Events
  84429. /**
  84430. * An observable triggered before computing the skeleton's matrices
  84431. */
  84432. this.onBeforeComputeObservable = new BABYLON.Observable();
  84433. this.bones = [];
  84434. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84435. scene.skeletons.push(this);
  84436. //make sure it will recalculate the matrix next time prepare is called.
  84437. this._isDirty = true;
  84438. }
  84439. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  84440. /**
  84441. * Gets or sets the animation properties override
  84442. */
  84443. get: function () {
  84444. if (!this._animationPropertiesOverride) {
  84445. return this._scene.animationPropertiesOverride;
  84446. }
  84447. return this._animationPropertiesOverride;
  84448. },
  84449. set: function (value) {
  84450. this._animationPropertiesOverride = value;
  84451. },
  84452. enumerable: true,
  84453. configurable: true
  84454. });
  84455. // Members
  84456. /**
  84457. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  84458. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  84459. * @returns a Float32Array containing matrices data
  84460. */
  84461. Skeleton.prototype.getTransformMatrices = function (mesh) {
  84462. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  84463. return mesh._bonesTransformMatrices;
  84464. }
  84465. if (!this._transformMatrices) {
  84466. this.prepare();
  84467. }
  84468. return this._transformMatrices;
  84469. };
  84470. /**
  84471. * Gets the current hosting scene
  84472. * @returns a scene object
  84473. */
  84474. Skeleton.prototype.getScene = function () {
  84475. return this._scene;
  84476. };
  84477. // Methods
  84478. /**
  84479. * Gets a string representing the current skeleton data
  84480. * @param fullDetails defines a boolean indicating if we want a verbose version
  84481. * @returns a string representing the current skeleton data
  84482. */
  84483. Skeleton.prototype.toString = function (fullDetails) {
  84484. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  84485. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  84486. if (fullDetails) {
  84487. ret += ", Ranges: {";
  84488. var first = true;
  84489. for (var name_1 in this._ranges) {
  84490. if (first) {
  84491. ret += ", ";
  84492. first = false;
  84493. }
  84494. ret += name_1;
  84495. }
  84496. ret += "}";
  84497. }
  84498. return ret;
  84499. };
  84500. /**
  84501. * Get bone's index searching by name
  84502. * @param name defines bone's name to search for
  84503. * @return the indice of the bone. Returns -1 if not found
  84504. */
  84505. Skeleton.prototype.getBoneIndexByName = function (name) {
  84506. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  84507. if (this.bones[boneIndex].name === name) {
  84508. return boneIndex;
  84509. }
  84510. }
  84511. return -1;
  84512. };
  84513. /**
  84514. * Creater a new animation range
  84515. * @param name defines the name of the range
  84516. * @param from defines the start key
  84517. * @param to defines the end key
  84518. */
  84519. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  84520. // check name not already in use
  84521. if (!this._ranges[name]) {
  84522. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  84523. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84524. if (this.bones[i].animations[0]) {
  84525. this.bones[i].animations[0].createRange(name, from, to);
  84526. }
  84527. }
  84528. }
  84529. };
  84530. /**
  84531. * Delete a specific animation range
  84532. * @param name defines the name of the range
  84533. * @param deleteFrames defines if frames must be removed as well
  84534. */
  84535. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  84536. if (deleteFrames === void 0) { deleteFrames = true; }
  84537. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84538. if (this.bones[i].animations[0]) {
  84539. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  84540. }
  84541. }
  84542. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  84543. };
  84544. /**
  84545. * Gets a specific animation range
  84546. * @param name defines the name of the range to look for
  84547. * @returns the requested animation range or null if not found
  84548. */
  84549. Skeleton.prototype.getAnimationRange = function (name) {
  84550. return this._ranges[name];
  84551. };
  84552. /**
  84553. * Gets the list of all animation ranges defined on this skeleton
  84554. * @returns an array
  84555. */
  84556. Skeleton.prototype.getAnimationRanges = function () {
  84557. var animationRanges = [];
  84558. var name;
  84559. var i = 0;
  84560. for (name in this._ranges) {
  84561. animationRanges[i] = this._ranges[name];
  84562. i++;
  84563. }
  84564. return animationRanges;
  84565. };
  84566. /**
  84567. * Copy animation range from a source skeleton.
  84568. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  84569. * @param source defines the source skeleton
  84570. * @param name defines the name of the range to copy
  84571. * @param rescaleAsRequired defines if rescaling must be applied if required
  84572. * @returns true if operation was successful
  84573. */
  84574. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  84575. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84576. if (this._ranges[name] || !source.getAnimationRange(name)) {
  84577. return false;
  84578. }
  84579. var ret = true;
  84580. var frameOffset = this._getHighestAnimationFrame() + 1;
  84581. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  84582. var boneDict = {};
  84583. var sourceBones = source.bones;
  84584. var nBones;
  84585. var i;
  84586. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  84587. boneDict[sourceBones[i].name] = sourceBones[i];
  84588. }
  84589. if (this.bones.length !== sourceBones.length) {
  84590. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  84591. ret = false;
  84592. }
  84593. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  84594. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  84595. var boneName = this.bones[i].name;
  84596. var sourceBone = boneDict[boneName];
  84597. if (sourceBone) {
  84598. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  84599. }
  84600. else {
  84601. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  84602. ret = false;
  84603. }
  84604. }
  84605. // do not call createAnimationRange(), since it also is done to bones, which was already done
  84606. var range = source.getAnimationRange(name);
  84607. if (range) {
  84608. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  84609. }
  84610. return ret;
  84611. };
  84612. /**
  84613. * Forces the skeleton to go to rest pose
  84614. */
  84615. Skeleton.prototype.returnToRest = function () {
  84616. for (var index = 0; index < this.bones.length; index++) {
  84617. this.bones[index].returnToRest();
  84618. }
  84619. };
  84620. Skeleton.prototype._getHighestAnimationFrame = function () {
  84621. var ret = 0;
  84622. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84623. if (this.bones[i].animations[0]) {
  84624. var highest = this.bones[i].animations[0].getHighestFrame();
  84625. if (ret < highest) {
  84626. ret = highest;
  84627. }
  84628. }
  84629. }
  84630. return ret;
  84631. };
  84632. /**
  84633. * Begin a specific animation range
  84634. * @param name defines the name of the range to start
  84635. * @param loop defines if looping must be turned on (false by default)
  84636. * @param speedRatio defines the speed ratio to apply (1 by default)
  84637. * @param onAnimationEnd defines a callback which will be called when animation will end
  84638. * @returns a new animatable
  84639. */
  84640. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  84641. var range = this.getAnimationRange(name);
  84642. if (!range) {
  84643. return null;
  84644. }
  84645. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  84646. };
  84647. /** @hidden */
  84648. Skeleton.prototype._markAsDirty = function () {
  84649. this._isDirty = true;
  84650. };
  84651. /** @hidden */
  84652. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  84653. this._meshesWithPoseMatrix.push(mesh);
  84654. };
  84655. /** @hidden */
  84656. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  84657. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  84658. if (index > -1) {
  84659. this._meshesWithPoseMatrix.splice(index, 1);
  84660. }
  84661. };
  84662. /** @hidden */
  84663. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  84664. this.onBeforeComputeObservable.notifyObservers(this);
  84665. for (var index = 0; index < this.bones.length; index++) {
  84666. var bone = this.bones[index];
  84667. var parentBone = bone.getParent();
  84668. if (parentBone) {
  84669. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  84670. }
  84671. else {
  84672. if (initialSkinMatrix) {
  84673. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  84674. }
  84675. else {
  84676. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  84677. }
  84678. }
  84679. if (bone._index !== -1) {
  84680. var mappedIndex = bone._index === null ? index : bone._index;
  84681. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  84682. }
  84683. }
  84684. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  84685. };
  84686. /**
  84687. * Build all resources required to render a skeleton
  84688. */
  84689. Skeleton.prototype.prepare = function () {
  84690. if (!this._isDirty) {
  84691. return;
  84692. }
  84693. if (this.needInitialSkinMatrix) {
  84694. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  84695. var mesh = this._meshesWithPoseMatrix[index];
  84696. var poseMatrix = mesh.getPoseMatrix();
  84697. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  84698. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84699. }
  84700. if (this._synchronizedWithMesh !== mesh) {
  84701. this._synchronizedWithMesh = mesh;
  84702. // Prepare bones
  84703. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  84704. var bone = this.bones[boneIndex];
  84705. if (!bone.getParent()) {
  84706. var matrix = bone.getBaseMatrix();
  84707. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  84708. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  84709. }
  84710. }
  84711. }
  84712. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  84713. }
  84714. }
  84715. else {
  84716. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  84717. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84718. }
  84719. this._computeTransformMatrices(this._transformMatrices, null);
  84720. }
  84721. this._isDirty = false;
  84722. this._scene._activeBones.addCount(this.bones.length, false);
  84723. };
  84724. /**
  84725. * Gets the list of animatables currently running for this skeleton
  84726. * @returns an array of animatables
  84727. */
  84728. Skeleton.prototype.getAnimatables = function () {
  84729. if (!this._animatables || this._animatables.length !== this.bones.length) {
  84730. this._animatables = [];
  84731. for (var index = 0; index < this.bones.length; index++) {
  84732. this._animatables.push(this.bones[index]);
  84733. }
  84734. }
  84735. return this._animatables;
  84736. };
  84737. /**
  84738. * Clone the current skeleton
  84739. * @param name defines the name of the new skeleton
  84740. * @param id defines the id of the enw skeleton
  84741. * @returns the new skeleton
  84742. */
  84743. Skeleton.prototype.clone = function (name, id) {
  84744. var result = new Skeleton(name, id || name, this._scene);
  84745. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84746. for (var index = 0; index < this.bones.length; index++) {
  84747. var source = this.bones[index];
  84748. var parentBone = null;
  84749. var parent_1 = source.getParent();
  84750. if (parent_1) {
  84751. var parentIndex = this.bones.indexOf(parent_1);
  84752. parentBone = result.bones[parentIndex];
  84753. }
  84754. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  84755. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  84756. }
  84757. if (this._ranges) {
  84758. result._ranges = {};
  84759. for (var rangeName in this._ranges) {
  84760. var range = this._ranges[rangeName];
  84761. if (range) {
  84762. result._ranges[rangeName] = range.clone();
  84763. }
  84764. }
  84765. }
  84766. this._isDirty = true;
  84767. return result;
  84768. };
  84769. /**
  84770. * Enable animation blending for this skeleton
  84771. * @param blendingSpeed defines the blending speed to apply
  84772. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  84773. */
  84774. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  84775. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  84776. this.bones.forEach(function (bone) {
  84777. bone.animations.forEach(function (animation) {
  84778. animation.enableBlending = true;
  84779. animation.blendingSpeed = blendingSpeed;
  84780. });
  84781. });
  84782. };
  84783. /**
  84784. * Releases all resources associated with the current skeleton
  84785. */
  84786. Skeleton.prototype.dispose = function () {
  84787. this._meshesWithPoseMatrix = [];
  84788. // Animations
  84789. this.getScene().stopAnimation(this);
  84790. // Remove from scene
  84791. this.getScene().removeSkeleton(this);
  84792. };
  84793. /**
  84794. * Serialize the skeleton in a JSON object
  84795. * @returns a JSON object
  84796. */
  84797. Skeleton.prototype.serialize = function () {
  84798. var serializationObject = {};
  84799. serializationObject.name = this.name;
  84800. serializationObject.id = this.id;
  84801. if (this.dimensionsAtRest) {
  84802. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  84803. }
  84804. serializationObject.bones = [];
  84805. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84806. for (var index = 0; index < this.bones.length; index++) {
  84807. var bone = this.bones[index];
  84808. var parent_2 = bone.getParent();
  84809. var serializedBone = {
  84810. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  84811. name: bone.name,
  84812. matrix: bone.getBaseMatrix().toArray(),
  84813. rest: bone.getRestPose().toArray()
  84814. };
  84815. serializationObject.bones.push(serializedBone);
  84816. if (bone.length) {
  84817. serializedBone.length = bone.length;
  84818. }
  84819. if (bone.metadata) {
  84820. serializedBone.metadata = bone.metadata;
  84821. }
  84822. if (bone.animations && bone.animations.length > 0) {
  84823. serializedBone.animation = bone.animations[0].serialize();
  84824. }
  84825. serializationObject.ranges = [];
  84826. for (var name in this._ranges) {
  84827. var source = this._ranges[name];
  84828. if (!source) {
  84829. continue;
  84830. }
  84831. var range = {};
  84832. range.name = name;
  84833. range.from = source.from;
  84834. range.to = source.to;
  84835. serializationObject.ranges.push(range);
  84836. }
  84837. }
  84838. return serializationObject;
  84839. };
  84840. /**
  84841. * Creates a new skeleton from serialized data
  84842. * @param parsedSkeleton defines the serialized data
  84843. * @param scene defines the hosting scene
  84844. * @returns a new skeleton
  84845. */
  84846. Skeleton.Parse = function (parsedSkeleton, scene) {
  84847. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  84848. if (parsedSkeleton.dimensionsAtRest) {
  84849. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  84850. }
  84851. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  84852. var index;
  84853. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  84854. var parsedBone = parsedSkeleton.bones[index];
  84855. var parentBone = null;
  84856. if (parsedBone.parentBoneIndex > -1) {
  84857. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  84858. }
  84859. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  84860. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  84861. if (parsedBone.length) {
  84862. bone.length = parsedBone.length;
  84863. }
  84864. if (parsedBone.metadata) {
  84865. bone.metadata = parsedBone.metadata;
  84866. }
  84867. if (parsedBone.animation) {
  84868. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  84869. }
  84870. }
  84871. // placed after bones, so createAnimationRange can cascade down
  84872. if (parsedSkeleton.ranges) {
  84873. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  84874. var data = parsedSkeleton.ranges[index];
  84875. skeleton.createAnimationRange(data.name, data.from, data.to);
  84876. }
  84877. }
  84878. return skeleton;
  84879. };
  84880. /**
  84881. * Compute all node absolute transforms
  84882. * @param forceUpdate defines if computation must be done even if cache is up to date
  84883. */
  84884. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  84885. if (forceUpdate === void 0) { forceUpdate = false; }
  84886. var renderId = this._scene.getRenderId();
  84887. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  84888. this.bones[0].computeAbsoluteTransforms();
  84889. this._lastAbsoluteTransformsUpdateId = renderId;
  84890. }
  84891. };
  84892. /**
  84893. * Gets the root pose matrix
  84894. * @returns a matrix
  84895. */
  84896. Skeleton.prototype.getPoseMatrix = function () {
  84897. var poseMatrix = null;
  84898. if (this._meshesWithPoseMatrix.length > 0) {
  84899. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  84900. }
  84901. return poseMatrix;
  84902. };
  84903. /**
  84904. * Sorts bones per internal index
  84905. */
  84906. Skeleton.prototype.sortBones = function () {
  84907. var bones = new Array();
  84908. var visited = new Array(this.bones.length);
  84909. for (var index = 0; index < this.bones.length; index++) {
  84910. this._sortBones(index, bones, visited);
  84911. }
  84912. this.bones = bones;
  84913. };
  84914. Skeleton.prototype._sortBones = function (index, bones, visited) {
  84915. if (visited[index]) {
  84916. return;
  84917. }
  84918. visited[index] = true;
  84919. var bone = this.bones[index];
  84920. if (bone._index === undefined) {
  84921. bone._index = index;
  84922. }
  84923. var parentBone = bone.getParent();
  84924. if (parentBone) {
  84925. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  84926. }
  84927. bones.push(bone);
  84928. };
  84929. return Skeleton;
  84930. }());
  84931. BABYLON.Skeleton = Skeleton;
  84932. })(BABYLON || (BABYLON = {}));
  84933. //# sourceMappingURL=babylon.skeleton.js.map
  84934. var BABYLON;
  84935. (function (BABYLON) {
  84936. ;
  84937. /**
  84938. * This groups tools to convert HDR texture to native colors array.
  84939. */
  84940. var HDRTools = /** @class */ (function () {
  84941. function HDRTools() {
  84942. }
  84943. HDRTools.Ldexp = function (mantissa, exponent) {
  84944. if (exponent > 1023) {
  84945. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  84946. }
  84947. if (exponent < -1074) {
  84948. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  84949. }
  84950. return mantissa * Math.pow(2, exponent);
  84951. };
  84952. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  84953. if (exponent > 0) { /*nonzero pixel*/
  84954. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  84955. float32array[index + 0] = red * exponent;
  84956. float32array[index + 1] = green * exponent;
  84957. float32array[index + 2] = blue * exponent;
  84958. }
  84959. else {
  84960. float32array[index + 0] = 0;
  84961. float32array[index + 1] = 0;
  84962. float32array[index + 2] = 0;
  84963. }
  84964. };
  84965. HDRTools.readStringLine = function (uint8array, startIndex) {
  84966. var line = "";
  84967. var character = "";
  84968. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  84969. character = String.fromCharCode(uint8array[i]);
  84970. if (character == "\n") {
  84971. break;
  84972. }
  84973. line += character;
  84974. }
  84975. return line;
  84976. };
  84977. /**
  84978. * Reads header information from an RGBE texture stored in a native array.
  84979. * More information on this format are available here:
  84980. * https://en.wikipedia.org/wiki/RGBE_image_format
  84981. *
  84982. * @param uint8array The binary file stored in native array.
  84983. * @return The header information.
  84984. */
  84985. HDRTools.RGBE_ReadHeader = function (uint8array) {
  84986. var height = 0;
  84987. var width = 0;
  84988. var line = this.readStringLine(uint8array, 0);
  84989. if (line[0] != '#' || line[1] != '?') {
  84990. throw "Bad HDR Format.";
  84991. }
  84992. var endOfHeader = false;
  84993. var findFormat = false;
  84994. var lineIndex = 0;
  84995. do {
  84996. lineIndex += (line.length + 1);
  84997. line = this.readStringLine(uint8array, lineIndex);
  84998. if (line == "FORMAT=32-bit_rle_rgbe") {
  84999. findFormat = true;
  85000. }
  85001. else if (line.length == 0) {
  85002. endOfHeader = true;
  85003. }
  85004. } while (!endOfHeader);
  85005. if (!findFormat) {
  85006. throw "HDR Bad header format, unsupported FORMAT";
  85007. }
  85008. lineIndex += (line.length + 1);
  85009. line = this.readStringLine(uint8array, lineIndex);
  85010. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  85011. var match = sizeRegexp.exec(line);
  85012. // TODO. Support +Y and -X if needed.
  85013. if (!match || match.length < 3) {
  85014. throw "HDR Bad header format, no size";
  85015. }
  85016. width = parseInt(match[2]);
  85017. height = parseInt(match[1]);
  85018. if (width < 8 || width > 0x7fff) {
  85019. throw "HDR Bad header format, unsupported size";
  85020. }
  85021. lineIndex += (line.length + 1);
  85022. return {
  85023. height: height,
  85024. width: width,
  85025. dataPosition: lineIndex
  85026. };
  85027. };
  85028. /**
  85029. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  85030. * This RGBE texture needs to store the information as a panorama.
  85031. *
  85032. * More information on this format are available here:
  85033. * https://en.wikipedia.org/wiki/RGBE_image_format
  85034. *
  85035. * @param buffer The binary file stored in an array buffer.
  85036. * @param size The expected size of the extracted cubemap.
  85037. * @return The Cube Map information.
  85038. */
  85039. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  85040. var uint8array = new Uint8Array(buffer);
  85041. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  85042. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85043. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  85044. return cubeMapData;
  85045. };
  85046. /**
  85047. * Returns the pixels data extracted from an RGBE texture.
  85048. * This pixels will be stored left to right up to down in the R G B order in one array.
  85049. *
  85050. * More information on this format are available here:
  85051. * https://en.wikipedia.org/wiki/RGBE_image_format
  85052. *
  85053. * @param uint8array The binary file stored in an array buffer.
  85054. * @param hdrInfo The header information of the file.
  85055. * @return The pixels data in RGB right to left up to down order.
  85056. */
  85057. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  85058. // Keep for multi format supports.
  85059. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  85060. };
  85061. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  85062. var num_scanlines = hdrInfo.height;
  85063. var scanline_width = hdrInfo.width;
  85064. var a, b, c, d, count;
  85065. var dataIndex = hdrInfo.dataPosition;
  85066. var index = 0, endIndex = 0, i = 0;
  85067. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  85068. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  85069. // 3 channels of 4 bytes per pixel in float.
  85070. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  85071. var resultArray = new Float32Array(resultBuffer);
  85072. // read in each successive scanline
  85073. while (num_scanlines > 0) {
  85074. a = uint8array[dataIndex++];
  85075. b = uint8array[dataIndex++];
  85076. c = uint8array[dataIndex++];
  85077. d = uint8array[dataIndex++];
  85078. if (a != 2 || b != 2 || (c & 0x80)) {
  85079. // this file is not run length encoded
  85080. throw "HDR Bad header format, not RLE";
  85081. }
  85082. if (((c << 8) | d) != scanline_width) {
  85083. throw "HDR Bad header format, wrong scan line width";
  85084. }
  85085. index = 0;
  85086. // read each of the four channels for the scanline into the buffer
  85087. for (i = 0; i < 4; i++) {
  85088. endIndex = (i + 1) * scanline_width;
  85089. while (index < endIndex) {
  85090. a = uint8array[dataIndex++];
  85091. b = uint8array[dataIndex++];
  85092. if (a > 128) {
  85093. // a run of the same value
  85094. count = a - 128;
  85095. if ((count == 0) || (count > endIndex - index)) {
  85096. throw "HDR Bad Format, bad scanline data (run)";
  85097. }
  85098. while (count-- > 0) {
  85099. scanLineArray[index++] = b;
  85100. }
  85101. }
  85102. else {
  85103. // a non-run
  85104. count = a;
  85105. if ((count == 0) || (count > endIndex - index)) {
  85106. throw "HDR Bad Format, bad scanline data (non-run)";
  85107. }
  85108. scanLineArray[index++] = b;
  85109. if (--count > 0) {
  85110. for (var j = 0; j < count; j++) {
  85111. scanLineArray[index++] = uint8array[dataIndex++];
  85112. }
  85113. }
  85114. }
  85115. }
  85116. }
  85117. // now convert data from buffer into floats
  85118. for (i = 0; i < scanline_width; i++) {
  85119. a = scanLineArray[i];
  85120. b = scanLineArray[i + scanline_width];
  85121. c = scanLineArray[i + 2 * scanline_width];
  85122. d = scanLineArray[i + 3 * scanline_width];
  85123. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  85124. }
  85125. num_scanlines--;
  85126. }
  85127. return resultArray;
  85128. };
  85129. return HDRTools;
  85130. }());
  85131. BABYLON.HDRTools = HDRTools;
  85132. })(BABYLON || (BABYLON = {}));
  85133. //# sourceMappingURL=babylon.hdr.js.map
  85134. var BABYLON;
  85135. (function (BABYLON) {
  85136. /**
  85137. * This represents a texture coming from an HDR input.
  85138. *
  85139. * The only supported format is currently panorama picture stored in RGBE format.
  85140. * Example of such files can be found on HDRLib: http://hdrlib.com/
  85141. */
  85142. var HDRCubeTexture = /** @class */ (function (_super) {
  85143. __extends(HDRCubeTexture, _super);
  85144. /**
  85145. * Instantiates an HDRTexture from the following parameters.
  85146. *
  85147. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  85148. * @param scene The scene the texture will be used in
  85149. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  85150. * @param noMipmap Forces to not generate the mipmap if true
  85151. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  85152. * @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)
  85153. * @param reserved Reserved flag for internal use.
  85154. */
  85155. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  85156. if (noMipmap === void 0) { noMipmap = false; }
  85157. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85158. if (gammaSpace === void 0) { gammaSpace = false; }
  85159. if (reserved === void 0) { reserved = false; }
  85160. if (onLoad === void 0) { onLoad = null; }
  85161. if (onError === void 0) { onError = null; }
  85162. var _this = _super.call(this, scene) || this;
  85163. _this._generateHarmonics = true;
  85164. _this._onLoad = null;
  85165. _this._onError = null;
  85166. /**
  85167. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  85168. */
  85169. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  85170. _this._isBlocking = true;
  85171. _this._rotationY = 0;
  85172. /**
  85173. * Gets or sets the center of the bounding box associated with the cube texture
  85174. * It must define where the camera used to render the texture was set
  85175. */
  85176. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  85177. if (!url) {
  85178. return _this;
  85179. }
  85180. _this.name = url;
  85181. _this.url = url;
  85182. _this.hasAlpha = false;
  85183. _this.isCube = true;
  85184. _this._textureMatrix = BABYLON.Matrix.Identity();
  85185. _this._onLoad = onLoad;
  85186. _this._onError = onError;
  85187. _this.gammaSpace = gammaSpace;
  85188. _this._noMipmap = noMipmap;
  85189. _this._size = size;
  85190. _this._texture = _this._getFromCache(url, _this._noMipmap);
  85191. if (!_this._texture) {
  85192. if (!scene.useDelayedTextureLoading) {
  85193. _this.loadTexture();
  85194. }
  85195. else {
  85196. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85197. }
  85198. }
  85199. return _this;
  85200. }
  85201. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  85202. /**
  85203. * Gets wether or not the texture is blocking during loading.
  85204. */
  85205. get: function () {
  85206. return this._isBlocking;
  85207. },
  85208. /**
  85209. * Sets wether or not the texture is blocking during loading.
  85210. */
  85211. set: function (value) {
  85212. this._isBlocking = value;
  85213. },
  85214. enumerable: true,
  85215. configurable: true
  85216. });
  85217. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  85218. /**
  85219. * Gets texture matrix rotation angle around Y axis radians.
  85220. */
  85221. get: function () {
  85222. return this._rotationY;
  85223. },
  85224. /**
  85225. * Sets texture matrix rotation angle around Y axis in radians.
  85226. */
  85227. set: function (value) {
  85228. this._rotationY = value;
  85229. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  85230. },
  85231. enumerable: true,
  85232. configurable: true
  85233. });
  85234. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  85235. get: function () {
  85236. return this._boundingBoxSize;
  85237. },
  85238. /**
  85239. * Gets or sets the size of the bounding box associated with the cube texture
  85240. * When defined, the cubemap will switch to local mode
  85241. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  85242. * @example https://www.babylonjs-playground.com/#RNASML
  85243. */
  85244. set: function (value) {
  85245. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  85246. return;
  85247. }
  85248. this._boundingBoxSize = value;
  85249. var scene = this.getScene();
  85250. if (scene) {
  85251. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  85252. }
  85253. },
  85254. enumerable: true,
  85255. configurable: true
  85256. });
  85257. /**
  85258. * Occurs when the file is raw .hdr file.
  85259. */
  85260. HDRCubeTexture.prototype.loadTexture = function () {
  85261. var _this = this;
  85262. var callback = function (buffer) {
  85263. _this.lodGenerationOffset = 0.0;
  85264. _this.lodGenerationScale = 0.8;
  85265. var scene = _this.getScene();
  85266. if (!scene) {
  85267. return null;
  85268. }
  85269. // Extract the raw linear data.
  85270. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  85271. // Generate harmonics if needed.
  85272. if (_this._generateHarmonics) {
  85273. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  85274. _this.sphericalPolynomial = sphericalPolynomial;
  85275. }
  85276. var results = [];
  85277. var byteArray = null;
  85278. // Push each faces.
  85279. for (var j = 0; j < 6; j++) {
  85280. // Create uintarray fallback.
  85281. if (!scene.getEngine().getCaps().textureFloat) {
  85282. // 3 channels of 1 bytes per pixel in bytes.
  85283. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  85284. byteArray = new Uint8Array(byteBuffer);
  85285. }
  85286. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  85287. // If special cases.
  85288. if (_this.gammaSpace || byteArray) {
  85289. for (var i = 0; i < _this._size * _this._size; i++) {
  85290. // Put in gamma space if requested.
  85291. if (_this.gammaSpace) {
  85292. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  85293. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  85294. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  85295. }
  85296. // Convert to int texture for fallback.
  85297. if (byteArray) {
  85298. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  85299. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  85300. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  85301. // May use luminance instead if the result is not accurate.
  85302. var max = Math.max(Math.max(r, g), b);
  85303. if (max > 255) {
  85304. var scale = 255 / max;
  85305. r *= scale;
  85306. g *= scale;
  85307. b *= scale;
  85308. }
  85309. byteArray[(i * 3) + 0] = r;
  85310. byteArray[(i * 3) + 1] = g;
  85311. byteArray[(i * 3) + 2] = b;
  85312. }
  85313. }
  85314. }
  85315. if (byteArray) {
  85316. results.push(byteArray);
  85317. }
  85318. else {
  85319. results.push(dataFace);
  85320. }
  85321. }
  85322. return results;
  85323. };
  85324. var scene = this.getScene();
  85325. if (scene) {
  85326. 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);
  85327. }
  85328. };
  85329. HDRCubeTexture.prototype.clone = function () {
  85330. var scene = this.getScene();
  85331. if (!scene) {
  85332. return this;
  85333. }
  85334. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  85335. // Base texture
  85336. newTexture.level = this.level;
  85337. newTexture.wrapU = this.wrapU;
  85338. newTexture.wrapV = this.wrapV;
  85339. newTexture.coordinatesIndex = this.coordinatesIndex;
  85340. newTexture.coordinatesMode = this.coordinatesMode;
  85341. return newTexture;
  85342. };
  85343. // Methods
  85344. HDRCubeTexture.prototype.delayLoad = function () {
  85345. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85346. return;
  85347. }
  85348. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85349. this._texture = this._getFromCache(this.url, this._noMipmap);
  85350. if (!this._texture) {
  85351. this.loadTexture();
  85352. }
  85353. };
  85354. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  85355. return this._textureMatrix;
  85356. };
  85357. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  85358. this._textureMatrix = value;
  85359. };
  85360. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85361. var texture = null;
  85362. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85363. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  85364. texture.name = parsedTexture.name;
  85365. texture.hasAlpha = parsedTexture.hasAlpha;
  85366. texture.level = parsedTexture.level;
  85367. texture.coordinatesMode = parsedTexture.coordinatesMode;
  85368. texture.isBlocking = parsedTexture.isBlocking;
  85369. }
  85370. if (texture) {
  85371. if (parsedTexture.boundingBoxPosition) {
  85372. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  85373. }
  85374. if (parsedTexture.boundingBoxSize) {
  85375. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  85376. }
  85377. if (parsedTexture.rotationY) {
  85378. texture.rotationY = parsedTexture.rotationY;
  85379. }
  85380. }
  85381. return texture;
  85382. };
  85383. HDRCubeTexture.prototype.serialize = function () {
  85384. if (!this.name) {
  85385. return null;
  85386. }
  85387. var serializationObject = {};
  85388. serializationObject.name = this.name;
  85389. serializationObject.hasAlpha = this.hasAlpha;
  85390. serializationObject.isCube = true;
  85391. serializationObject.level = this.level;
  85392. serializationObject.size = this._size;
  85393. serializationObject.coordinatesMode = this.coordinatesMode;
  85394. serializationObject.useInGammaSpace = this.gammaSpace;
  85395. serializationObject.generateHarmonics = this._generateHarmonics;
  85396. serializationObject.customType = "BABYLON.HDRCubeTexture";
  85397. serializationObject.noMipmap = this._noMipmap;
  85398. serializationObject.isBlocking = this._isBlocking;
  85399. serializationObject.rotationY = this._rotationY;
  85400. return serializationObject;
  85401. };
  85402. HDRCubeTexture._facesMapping = [
  85403. "right",
  85404. "left",
  85405. "up",
  85406. "down",
  85407. "front",
  85408. "back"
  85409. ];
  85410. return HDRCubeTexture;
  85411. }(BABYLON.BaseTexture));
  85412. BABYLON.HDRCubeTexture = HDRCubeTexture;
  85413. })(BABYLON || (BABYLON = {}));
  85414. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  85415. var BABYLON;
  85416. (function (BABYLON) {
  85417. /**
  85418. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  85419. */
  85420. var PanoramaToCubeMapTools = /** @class */ (function () {
  85421. function PanoramaToCubeMapTools() {
  85422. }
  85423. /**
  85424. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  85425. *
  85426. * @param float32Array The source data.
  85427. * @param inputWidth The width of the input panorama.
  85428. * @param inputhHeight The height of the input panorama.
  85429. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  85430. * @return The cubemap data
  85431. */
  85432. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  85433. if (!float32Array) {
  85434. throw "ConvertPanoramaToCubemap: input cannot be null";
  85435. }
  85436. if (float32Array.length != inputWidth * inputHeight * 3) {
  85437. throw "ConvertPanoramaToCubemap: input size is wrong";
  85438. }
  85439. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  85440. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  85441. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  85442. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  85443. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  85444. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  85445. return {
  85446. front: textureFront,
  85447. back: textureBack,
  85448. left: textureLeft,
  85449. right: textureRight,
  85450. up: textureUp,
  85451. down: textureDown,
  85452. size: size,
  85453. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85454. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  85455. gammaSpace: false,
  85456. };
  85457. };
  85458. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  85459. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  85460. var textureArray = new Float32Array(buffer);
  85461. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  85462. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  85463. var dy = 1 / texSize;
  85464. var fy = 0;
  85465. for (var y = 0; y < texSize; y++) {
  85466. var xv1 = faceData[0];
  85467. var xv2 = faceData[2];
  85468. for (var x = 0; x < texSize; x++) {
  85469. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  85470. v.normalize();
  85471. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  85472. // 3 channels per pixels
  85473. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  85474. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  85475. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  85476. xv1 = xv1.add(rotDX1);
  85477. xv2 = xv2.add(rotDX2);
  85478. }
  85479. fy += dy;
  85480. }
  85481. return textureArray;
  85482. };
  85483. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  85484. var theta = Math.atan2(vDir.z, vDir.x);
  85485. var phi = Math.acos(vDir.y);
  85486. while (theta < -Math.PI)
  85487. theta += 2 * Math.PI;
  85488. while (theta > Math.PI)
  85489. theta -= 2 * Math.PI;
  85490. var dx = theta / Math.PI;
  85491. var dy = phi / Math.PI;
  85492. // recenter.
  85493. dx = dx * 0.5 + 0.5;
  85494. var px = Math.round(dx * inputWidth);
  85495. if (px < 0)
  85496. px = 0;
  85497. else if (px >= inputWidth)
  85498. px = inputWidth - 1;
  85499. var py = Math.round(dy * inputHeight);
  85500. if (py < 0)
  85501. py = 0;
  85502. else if (py >= inputHeight)
  85503. py = inputHeight - 1;
  85504. var inputY = (inputHeight - py - 1);
  85505. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  85506. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  85507. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  85508. return {
  85509. r: r,
  85510. g: g,
  85511. b: b
  85512. };
  85513. };
  85514. PanoramaToCubeMapTools.FACE_FRONT = [
  85515. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85516. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85517. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85518. new BABYLON.Vector3(1.0, 1.0, -1.0)
  85519. ];
  85520. PanoramaToCubeMapTools.FACE_BACK = [
  85521. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85522. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85523. new BABYLON.Vector3(1.0, 1.0, 1.0),
  85524. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  85525. ];
  85526. PanoramaToCubeMapTools.FACE_RIGHT = [
  85527. new BABYLON.Vector3(1.0, -1.0, -1.0),
  85528. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85529. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85530. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85531. ];
  85532. PanoramaToCubeMapTools.FACE_LEFT = [
  85533. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85534. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85535. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85536. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  85537. ];
  85538. PanoramaToCubeMapTools.FACE_DOWN = [
  85539. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  85540. new BABYLON.Vector3(1.0, 1.0, -1.0),
  85541. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  85542. new BABYLON.Vector3(1.0, 1.0, 1.0)
  85543. ];
  85544. PanoramaToCubeMapTools.FACE_UP = [
  85545. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  85546. new BABYLON.Vector3(1.0, -1.0, 1.0),
  85547. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  85548. new BABYLON.Vector3(1.0, -1.0, -1.0)
  85549. ];
  85550. return PanoramaToCubeMapTools;
  85551. }());
  85552. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  85553. })(BABYLON || (BABYLON = {}));
  85554. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  85555. var BABYLON;
  85556. (function (BABYLON) {
  85557. var IndexedVector2 = /** @class */ (function (_super) {
  85558. __extends(IndexedVector2, _super);
  85559. function IndexedVector2(original, index) {
  85560. var _this = _super.call(this, original.x, original.y) || this;
  85561. _this.index = index;
  85562. return _this;
  85563. }
  85564. return IndexedVector2;
  85565. }(BABYLON.Vector2));
  85566. var PolygonPoints = /** @class */ (function () {
  85567. function PolygonPoints() {
  85568. this.elements = new Array();
  85569. }
  85570. PolygonPoints.prototype.add = function (originalPoints) {
  85571. var _this = this;
  85572. var result = new Array();
  85573. originalPoints.forEach(function (point) {
  85574. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  85575. var newPoint = new IndexedVector2(point, _this.elements.length);
  85576. result.push(newPoint);
  85577. _this.elements.push(newPoint);
  85578. }
  85579. });
  85580. return result;
  85581. };
  85582. PolygonPoints.prototype.computeBounds = function () {
  85583. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85584. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85585. this.elements.forEach(function (point) {
  85586. // x
  85587. if (point.x < lmin.x) {
  85588. lmin.x = point.x;
  85589. }
  85590. else if (point.x > lmax.x) {
  85591. lmax.x = point.x;
  85592. }
  85593. // y
  85594. if (point.y < lmin.y) {
  85595. lmin.y = point.y;
  85596. }
  85597. else if (point.y > lmax.y) {
  85598. lmax.y = point.y;
  85599. }
  85600. });
  85601. return {
  85602. min: lmin,
  85603. max: lmax,
  85604. width: lmax.x - lmin.x,
  85605. height: lmax.y - lmin.y
  85606. };
  85607. };
  85608. return PolygonPoints;
  85609. }());
  85610. var Polygon = /** @class */ (function () {
  85611. function Polygon() {
  85612. }
  85613. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  85614. return [
  85615. new BABYLON.Vector2(xmin, ymin),
  85616. new BABYLON.Vector2(xmax, ymin),
  85617. new BABYLON.Vector2(xmax, ymax),
  85618. new BABYLON.Vector2(xmin, ymax)
  85619. ];
  85620. };
  85621. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  85622. if (cx === void 0) { cx = 0; }
  85623. if (cy === void 0) { cy = 0; }
  85624. if (numberOfSides === void 0) { numberOfSides = 32; }
  85625. var result = new Array();
  85626. var angle = 0;
  85627. var increment = (Math.PI * 2) / numberOfSides;
  85628. for (var i = 0; i < numberOfSides; i++) {
  85629. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  85630. angle -= increment;
  85631. }
  85632. return result;
  85633. };
  85634. Polygon.Parse = function (input) {
  85635. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  85636. var i, result = [];
  85637. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  85638. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  85639. }
  85640. return result;
  85641. };
  85642. Polygon.StartingAt = function (x, y) {
  85643. return BABYLON.Path2.StartingAt(x, y);
  85644. };
  85645. return Polygon;
  85646. }());
  85647. BABYLON.Polygon = Polygon;
  85648. var PolygonMeshBuilder = /** @class */ (function () {
  85649. function PolygonMeshBuilder(name, contours, scene) {
  85650. this._points = new PolygonPoints();
  85651. this._outlinepoints = new PolygonPoints();
  85652. this._holes = new Array();
  85653. this._epoints = new Array();
  85654. this._eholes = new Array();
  85655. this._name = name;
  85656. this._scene = scene;
  85657. var points;
  85658. if (contours instanceof BABYLON.Path2) {
  85659. points = contours.getPoints();
  85660. }
  85661. else {
  85662. points = contours;
  85663. }
  85664. this._addToepoint(points);
  85665. this._points.add(points);
  85666. this._outlinepoints.add(points);
  85667. if (typeof earcut === 'undefined') {
  85668. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  85669. }
  85670. }
  85671. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  85672. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  85673. var p = points_1[_i];
  85674. this._epoints.push(p.x, p.y);
  85675. }
  85676. };
  85677. PolygonMeshBuilder.prototype.addHole = function (hole) {
  85678. this._points.add(hole);
  85679. var holepoints = new PolygonPoints();
  85680. holepoints.add(hole);
  85681. this._holes.push(holepoints);
  85682. this._eholes.push(this._epoints.length / 2);
  85683. this._addToepoint(hole);
  85684. return this;
  85685. };
  85686. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  85687. var _this = this;
  85688. if (updatable === void 0) { updatable = false; }
  85689. if (depth === void 0) { depth = 0; }
  85690. var result = new BABYLON.Mesh(this._name, this._scene);
  85691. var normals = new Array();
  85692. var positions = new Array();
  85693. var uvs = new Array();
  85694. var bounds = this._points.computeBounds();
  85695. this._points.elements.forEach(function (p) {
  85696. normals.push(0, 1.0, 0);
  85697. positions.push(p.x, 0, p.y);
  85698. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  85699. });
  85700. var indices = new Array();
  85701. var res = earcut(this._epoints, this._eholes, 2);
  85702. for (var i = 0; i < res.length; i++) {
  85703. indices.push(res[i]);
  85704. }
  85705. if (depth > 0) {
  85706. var positionscount = (positions.length / 3); //get the current pointcount
  85707. this._points.elements.forEach(function (p) {
  85708. normals.push(0, -1.0, 0);
  85709. positions.push(p.x, -depth, p.y);
  85710. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  85711. });
  85712. var totalCount = indices.length;
  85713. for (var i = 0; i < totalCount; i += 3) {
  85714. var i0 = indices[i + 0];
  85715. var i1 = indices[i + 1];
  85716. var i2 = indices[i + 2];
  85717. indices.push(i2 + positionscount);
  85718. indices.push(i1 + positionscount);
  85719. indices.push(i0 + positionscount);
  85720. }
  85721. //Add the sides
  85722. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  85723. this._holes.forEach(function (hole) {
  85724. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  85725. });
  85726. }
  85727. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  85728. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  85729. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  85730. result.setIndices(indices);
  85731. return result;
  85732. };
  85733. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  85734. var StartIndex = positions.length / 3;
  85735. var ulength = 0;
  85736. for (var i = 0; i < points.elements.length; i++) {
  85737. var p = points.elements[i];
  85738. var p1;
  85739. if ((i + 1) > points.elements.length - 1) {
  85740. p1 = points.elements[0];
  85741. }
  85742. else {
  85743. p1 = points.elements[i + 1];
  85744. }
  85745. positions.push(p.x, 0, p.y);
  85746. positions.push(p.x, -depth, p.y);
  85747. positions.push(p1.x, 0, p1.y);
  85748. positions.push(p1.x, -depth, p1.y);
  85749. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  85750. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  85751. var v3 = v2.subtract(v1);
  85752. var v4 = new BABYLON.Vector3(0, 1, 0);
  85753. var vn = BABYLON.Vector3.Cross(v3, v4);
  85754. vn = vn.normalize();
  85755. uvs.push(ulength / bounds.width, 0);
  85756. uvs.push(ulength / bounds.width, 1);
  85757. ulength += v3.length();
  85758. uvs.push((ulength / bounds.width), 0);
  85759. uvs.push((ulength / bounds.width), 1);
  85760. if (!flip) {
  85761. normals.push(-vn.x, -vn.y, -vn.z);
  85762. normals.push(-vn.x, -vn.y, -vn.z);
  85763. normals.push(-vn.x, -vn.y, -vn.z);
  85764. normals.push(-vn.x, -vn.y, -vn.z);
  85765. indices.push(StartIndex);
  85766. indices.push(StartIndex + 1);
  85767. indices.push(StartIndex + 2);
  85768. indices.push(StartIndex + 1);
  85769. indices.push(StartIndex + 3);
  85770. indices.push(StartIndex + 2);
  85771. }
  85772. else {
  85773. normals.push(vn.x, vn.y, vn.z);
  85774. normals.push(vn.x, vn.y, vn.z);
  85775. normals.push(vn.x, vn.y, vn.z);
  85776. normals.push(vn.x, vn.y, vn.z);
  85777. indices.push(StartIndex);
  85778. indices.push(StartIndex + 2);
  85779. indices.push(StartIndex + 1);
  85780. indices.push(StartIndex + 1);
  85781. indices.push(StartIndex + 2);
  85782. indices.push(StartIndex + 3);
  85783. }
  85784. StartIndex += 4;
  85785. }
  85786. ;
  85787. };
  85788. return PolygonMeshBuilder;
  85789. }());
  85790. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  85791. })(BABYLON || (BABYLON = {}));
  85792. //# sourceMappingURL=babylon.polygonMesh.js.map
  85793. var BABYLON;
  85794. (function (BABYLON) {
  85795. // Unique ID when we import meshes from Babylon to CSG
  85796. var currentCSGMeshId = 0;
  85797. // # class Vertex
  85798. // Represents a vertex of a polygon. Use your own vertex class instead of this
  85799. // one to provide additional features like texture coordinates and vertex
  85800. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  85801. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  85802. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  85803. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  85804. // is not used anywhere else.
  85805. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  85806. var Vertex = /** @class */ (function () {
  85807. function Vertex(pos, normal, uv) {
  85808. this.pos = pos;
  85809. this.normal = normal;
  85810. this.uv = uv;
  85811. }
  85812. Vertex.prototype.clone = function () {
  85813. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  85814. };
  85815. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  85816. // orientation of a polygon is flipped.
  85817. Vertex.prototype.flip = function () {
  85818. this.normal = this.normal.scale(-1);
  85819. };
  85820. // Create a new vertex between this vertex and `other` by linearly
  85821. // interpolating all properties using a parameter of `t`. Subclasses should
  85822. // override this to interpolate additional properties.
  85823. Vertex.prototype.interpolate = function (other, t) {
  85824. 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));
  85825. };
  85826. return Vertex;
  85827. }());
  85828. // # class Plane
  85829. // Represents a plane in 3D space.
  85830. var Plane = /** @class */ (function () {
  85831. function Plane(normal, w) {
  85832. this.normal = normal;
  85833. this.w = w;
  85834. }
  85835. Plane.FromPoints = function (a, b, c) {
  85836. var v0 = c.subtract(a);
  85837. var v1 = b.subtract(a);
  85838. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  85839. return null;
  85840. }
  85841. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  85842. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  85843. };
  85844. Plane.prototype.clone = function () {
  85845. return new Plane(this.normal.clone(), this.w);
  85846. };
  85847. Plane.prototype.flip = function () {
  85848. this.normal.scaleInPlace(-1);
  85849. this.w = -this.w;
  85850. };
  85851. // Split `polygon` by this plane if needed, then put the polygon or polygon
  85852. // fragments in the appropriate lists. Coplanar polygons go into either
  85853. // `coplanarFront` or `coplanarBack` depending on their orientation with
  85854. // respect to this plane. Polygons in front or in back of this plane go into
  85855. // either `front` or `back`.
  85856. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  85857. var COPLANAR = 0;
  85858. var FRONT = 1;
  85859. var BACK = 2;
  85860. var SPANNING = 3;
  85861. // Classify each point as well as the entire polygon into one of the above
  85862. // four classes.
  85863. var polygonType = 0;
  85864. var types = [];
  85865. var i;
  85866. var t;
  85867. for (i = 0; i < polygon.vertices.length; i++) {
  85868. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  85869. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  85870. polygonType |= type;
  85871. types.push(type);
  85872. }
  85873. // Put the polygon in the correct list, splitting it when necessary.
  85874. switch (polygonType) {
  85875. case COPLANAR:
  85876. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  85877. break;
  85878. case FRONT:
  85879. front.push(polygon);
  85880. break;
  85881. case BACK:
  85882. back.push(polygon);
  85883. break;
  85884. case SPANNING:
  85885. var f = [], b = [];
  85886. for (i = 0; i < polygon.vertices.length; i++) {
  85887. var j = (i + 1) % polygon.vertices.length;
  85888. var ti = types[i], tj = types[j];
  85889. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  85890. if (ti !== BACK)
  85891. f.push(vi);
  85892. if (ti !== FRONT)
  85893. b.push(ti !== BACK ? vi.clone() : vi);
  85894. if ((ti | tj) === SPANNING) {
  85895. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  85896. var v = vi.interpolate(vj, t);
  85897. f.push(v);
  85898. b.push(v.clone());
  85899. }
  85900. }
  85901. var poly;
  85902. if (f.length >= 3) {
  85903. poly = new Polygon(f, polygon.shared);
  85904. if (poly.plane)
  85905. front.push(poly);
  85906. }
  85907. if (b.length >= 3) {
  85908. poly = new Polygon(b, polygon.shared);
  85909. if (poly.plane)
  85910. back.push(poly);
  85911. }
  85912. break;
  85913. }
  85914. };
  85915. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  85916. // point is on the plane.
  85917. Plane.EPSILON = 1e-5;
  85918. return Plane;
  85919. }());
  85920. // # class Polygon
  85921. // Represents a convex polygon. The vertices used to initialize a polygon must
  85922. // be coplanar and form a convex loop.
  85923. //
  85924. // Each convex polygon has a `shared` property, which is shared between all
  85925. // polygons that are clones of each other or were split from the same polygon.
  85926. // This can be used to define per-polygon properties (such as surface color).
  85927. var Polygon = /** @class */ (function () {
  85928. function Polygon(vertices, shared) {
  85929. this.vertices = vertices;
  85930. this.shared = shared;
  85931. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  85932. }
  85933. Polygon.prototype.clone = function () {
  85934. var vertices = this.vertices.map(function (v) { return v.clone(); });
  85935. return new Polygon(vertices, this.shared);
  85936. };
  85937. Polygon.prototype.flip = function () {
  85938. this.vertices.reverse().map(function (v) { v.flip(); });
  85939. this.plane.flip();
  85940. };
  85941. return Polygon;
  85942. }());
  85943. // # class Node
  85944. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  85945. // by picking a polygon to split along. That polygon (and all other coplanar
  85946. // polygons) are added directly to that node and the other polygons are added to
  85947. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  85948. // no distinction between internal and leaf nodes.
  85949. var Node = /** @class */ (function () {
  85950. function Node(polygons) {
  85951. this.plane = null;
  85952. this.front = null;
  85953. this.back = null;
  85954. this.polygons = new Array();
  85955. if (polygons) {
  85956. this.build(polygons);
  85957. }
  85958. }
  85959. Node.prototype.clone = function () {
  85960. var node = new Node();
  85961. node.plane = this.plane && this.plane.clone();
  85962. node.front = this.front && this.front.clone();
  85963. node.back = this.back && this.back.clone();
  85964. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  85965. return node;
  85966. };
  85967. // Convert solid space to empty space and empty space to solid space.
  85968. Node.prototype.invert = function () {
  85969. for (var i = 0; i < this.polygons.length; i++) {
  85970. this.polygons[i].flip();
  85971. }
  85972. if (this.plane) {
  85973. this.plane.flip();
  85974. }
  85975. if (this.front) {
  85976. this.front.invert();
  85977. }
  85978. if (this.back) {
  85979. this.back.invert();
  85980. }
  85981. var temp = this.front;
  85982. this.front = this.back;
  85983. this.back = temp;
  85984. };
  85985. // Recursively remove all polygons in `polygons` that are inside this BSP
  85986. // tree.
  85987. Node.prototype.clipPolygons = function (polygons) {
  85988. if (!this.plane)
  85989. return polygons.slice();
  85990. var front = new Array(), back = new Array();
  85991. for (var i = 0; i < polygons.length; i++) {
  85992. this.plane.splitPolygon(polygons[i], front, back, front, back);
  85993. }
  85994. if (this.front) {
  85995. front = this.front.clipPolygons(front);
  85996. }
  85997. if (this.back) {
  85998. back = this.back.clipPolygons(back);
  85999. }
  86000. else {
  86001. back = [];
  86002. }
  86003. return front.concat(back);
  86004. };
  86005. // Remove all polygons in this BSP tree that are inside the other BSP tree
  86006. // `bsp`.
  86007. Node.prototype.clipTo = function (bsp) {
  86008. this.polygons = bsp.clipPolygons(this.polygons);
  86009. if (this.front)
  86010. this.front.clipTo(bsp);
  86011. if (this.back)
  86012. this.back.clipTo(bsp);
  86013. };
  86014. // Return a list of all polygons in this BSP tree.
  86015. Node.prototype.allPolygons = function () {
  86016. var polygons = this.polygons.slice();
  86017. if (this.front)
  86018. polygons = polygons.concat(this.front.allPolygons());
  86019. if (this.back)
  86020. polygons = polygons.concat(this.back.allPolygons());
  86021. return polygons;
  86022. };
  86023. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  86024. // new polygons are filtered down to the bottom of the tree and become new
  86025. // nodes there. Each set of polygons is partitioned using the first polygon
  86026. // (no heuristic is used to pick a good split).
  86027. Node.prototype.build = function (polygons) {
  86028. if (!polygons.length)
  86029. return;
  86030. if (!this.plane)
  86031. this.plane = polygons[0].plane.clone();
  86032. var front = new Array(), back = new Array();
  86033. for (var i = 0; i < polygons.length; i++) {
  86034. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  86035. }
  86036. if (front.length) {
  86037. if (!this.front)
  86038. this.front = new Node();
  86039. this.front.build(front);
  86040. }
  86041. if (back.length) {
  86042. if (!this.back)
  86043. this.back = new Node();
  86044. this.back.build(back);
  86045. }
  86046. };
  86047. return Node;
  86048. }());
  86049. var CSG = /** @class */ (function () {
  86050. function CSG() {
  86051. this.polygons = new Array();
  86052. }
  86053. // Convert BABYLON.Mesh to BABYLON.CSG
  86054. CSG.FromMesh = function (mesh) {
  86055. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  86056. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  86057. if (mesh instanceof BABYLON.Mesh) {
  86058. mesh.computeWorldMatrix(true);
  86059. matrix = mesh.getWorldMatrix();
  86060. meshPosition = mesh.position.clone();
  86061. meshRotation = mesh.rotation.clone();
  86062. if (mesh.rotationQuaternion) {
  86063. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  86064. }
  86065. meshScaling = mesh.scaling.clone();
  86066. }
  86067. else {
  86068. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  86069. }
  86070. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  86071. var subMeshes = mesh.subMeshes;
  86072. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  86073. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  86074. vertices = [];
  86075. for (var j = 0; j < 3; j++) {
  86076. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  86077. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  86078. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  86079. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  86080. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  86081. vertex = new Vertex(position, normal, uv);
  86082. vertices.push(vertex);
  86083. }
  86084. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  86085. // To handle the case of degenerated triangle
  86086. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  86087. if (polygon.plane)
  86088. polygons.push(polygon);
  86089. }
  86090. }
  86091. var csg = CSG.FromPolygons(polygons);
  86092. csg.matrix = matrix;
  86093. csg.position = meshPosition;
  86094. csg.rotation = meshRotation;
  86095. csg.scaling = meshScaling;
  86096. csg.rotationQuaternion = meshRotationQuaternion;
  86097. currentCSGMeshId++;
  86098. return csg;
  86099. };
  86100. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  86101. CSG.FromPolygons = function (polygons) {
  86102. var csg = new CSG();
  86103. csg.polygons = polygons;
  86104. return csg;
  86105. };
  86106. CSG.prototype.clone = function () {
  86107. var csg = new CSG();
  86108. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  86109. csg.copyTransformAttributes(this);
  86110. return csg;
  86111. };
  86112. CSG.prototype.union = function (csg) {
  86113. var a = new Node(this.clone().polygons);
  86114. var b = new Node(csg.clone().polygons);
  86115. a.clipTo(b);
  86116. b.clipTo(a);
  86117. b.invert();
  86118. b.clipTo(a);
  86119. b.invert();
  86120. a.build(b.allPolygons());
  86121. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86122. };
  86123. CSG.prototype.unionInPlace = function (csg) {
  86124. var a = new Node(this.polygons);
  86125. var b = new Node(csg.polygons);
  86126. a.clipTo(b);
  86127. b.clipTo(a);
  86128. b.invert();
  86129. b.clipTo(a);
  86130. b.invert();
  86131. a.build(b.allPolygons());
  86132. this.polygons = a.allPolygons();
  86133. };
  86134. CSG.prototype.subtract = function (csg) {
  86135. var a = new Node(this.clone().polygons);
  86136. var b = new Node(csg.clone().polygons);
  86137. a.invert();
  86138. a.clipTo(b);
  86139. b.clipTo(a);
  86140. b.invert();
  86141. b.clipTo(a);
  86142. b.invert();
  86143. a.build(b.allPolygons());
  86144. a.invert();
  86145. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86146. };
  86147. CSG.prototype.subtractInPlace = function (csg) {
  86148. var a = new Node(this.polygons);
  86149. var b = new Node(csg.polygons);
  86150. a.invert();
  86151. a.clipTo(b);
  86152. b.clipTo(a);
  86153. b.invert();
  86154. b.clipTo(a);
  86155. b.invert();
  86156. a.build(b.allPolygons());
  86157. a.invert();
  86158. this.polygons = a.allPolygons();
  86159. };
  86160. CSG.prototype.intersect = function (csg) {
  86161. var a = new Node(this.clone().polygons);
  86162. var b = new Node(csg.clone().polygons);
  86163. a.invert();
  86164. b.clipTo(a);
  86165. b.invert();
  86166. a.clipTo(b);
  86167. b.clipTo(a);
  86168. a.build(b.allPolygons());
  86169. a.invert();
  86170. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  86171. };
  86172. CSG.prototype.intersectInPlace = function (csg) {
  86173. var a = new Node(this.polygons);
  86174. var b = new Node(csg.polygons);
  86175. a.invert();
  86176. b.clipTo(a);
  86177. b.invert();
  86178. a.clipTo(b);
  86179. b.clipTo(a);
  86180. a.build(b.allPolygons());
  86181. a.invert();
  86182. this.polygons = a.allPolygons();
  86183. };
  86184. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  86185. // not modified.
  86186. CSG.prototype.inverse = function () {
  86187. var csg = this.clone();
  86188. csg.inverseInPlace();
  86189. return csg;
  86190. };
  86191. CSG.prototype.inverseInPlace = function () {
  86192. this.polygons.map(function (p) { p.flip(); });
  86193. };
  86194. // This is used to keep meshes transformations so they can be restored
  86195. // when we build back a Babylon Mesh
  86196. // NB : All CSG operations are performed in world coordinates
  86197. CSG.prototype.copyTransformAttributes = function (csg) {
  86198. this.matrix = csg.matrix;
  86199. this.position = csg.position;
  86200. this.rotation = csg.rotation;
  86201. this.scaling = csg.scaling;
  86202. this.rotationQuaternion = csg.rotationQuaternion;
  86203. return this;
  86204. };
  86205. // Build Raw mesh from CSG
  86206. // Coordinates here are in world space
  86207. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  86208. var matrix = this.matrix.clone();
  86209. matrix.invert();
  86210. 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;
  86211. if (keepSubMeshes) {
  86212. // Sort Polygons, since subMeshes are indices range
  86213. polygons.sort(function (a, b) {
  86214. if (a.shared.meshId === b.shared.meshId) {
  86215. return a.shared.subMeshId - b.shared.subMeshId;
  86216. }
  86217. else {
  86218. return a.shared.meshId - b.shared.meshId;
  86219. }
  86220. });
  86221. }
  86222. for (var i = 0, il = polygons.length; i < il; i++) {
  86223. polygon = polygons[i];
  86224. // Building SubMeshes
  86225. if (!subMesh_dict[polygon.shared.meshId]) {
  86226. subMesh_dict[polygon.shared.meshId] = {};
  86227. }
  86228. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  86229. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  86230. indexStart: +Infinity,
  86231. indexEnd: -Infinity,
  86232. materialIndex: polygon.shared.materialIndex
  86233. };
  86234. }
  86235. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  86236. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  86237. polygonIndices[0] = 0;
  86238. polygonIndices[1] = j - 1;
  86239. polygonIndices[2] = j;
  86240. for (var k = 0; k < 3; k++) {
  86241. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  86242. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  86243. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  86244. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  86245. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  86246. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  86247. // Check if 2 points can be merged
  86248. if (!(typeof vertex_idx !== 'undefined' &&
  86249. normals[vertex_idx * 3] === localNormal.x &&
  86250. normals[vertex_idx * 3 + 1] === localNormal.y &&
  86251. normals[vertex_idx * 3 + 2] === localNormal.z &&
  86252. uvs[vertex_idx * 2] === uv.x &&
  86253. uvs[vertex_idx * 2 + 1] === uv.y)) {
  86254. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  86255. uvs.push(uv.x, uv.y);
  86256. normals.push(normal.x, normal.y, normal.z);
  86257. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  86258. }
  86259. indices.push(vertex_idx);
  86260. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  86261. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  86262. currentIndex++;
  86263. }
  86264. }
  86265. }
  86266. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  86267. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  86268. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  86269. mesh.setIndices(indices, null);
  86270. if (keepSubMeshes) {
  86271. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  86272. var materialIndexOffset = 0, materialMaxIndex;
  86273. mesh.subMeshes = new Array();
  86274. for (var m in subMesh_dict) {
  86275. materialMaxIndex = -1;
  86276. for (var sm in subMesh_dict[m]) {
  86277. subMesh_obj = subMesh_dict[m][sm];
  86278. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  86279. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  86280. }
  86281. materialIndexOffset += ++materialMaxIndex;
  86282. }
  86283. }
  86284. return mesh;
  86285. };
  86286. // Build Mesh from CSG taking material and transforms into account
  86287. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  86288. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  86289. mesh.material = material;
  86290. mesh.position.copyFrom(this.position);
  86291. mesh.rotation.copyFrom(this.rotation);
  86292. if (this.rotationQuaternion) {
  86293. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  86294. }
  86295. mesh.scaling.copyFrom(this.scaling);
  86296. mesh.computeWorldMatrix(true);
  86297. return mesh;
  86298. };
  86299. return CSG;
  86300. }());
  86301. BABYLON.CSG = CSG;
  86302. })(BABYLON || (BABYLON = {}));
  86303. //# sourceMappingURL=babylon.csg.js.map
  86304. var BABYLON;
  86305. (function (BABYLON) {
  86306. var LensFlare = /** @class */ (function () {
  86307. function LensFlare(size, position, color, imgUrl, system) {
  86308. this.size = size;
  86309. this.position = position;
  86310. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  86311. this.color = color || new BABYLON.Color3(1, 1, 1);
  86312. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  86313. this._system = system;
  86314. system.lensFlares.push(this);
  86315. }
  86316. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  86317. return new LensFlare(size, position, color, imgUrl, system);
  86318. };
  86319. LensFlare.prototype.dispose = function () {
  86320. if (this.texture) {
  86321. this.texture.dispose();
  86322. }
  86323. // Remove from scene
  86324. var index = this._system.lensFlares.indexOf(this);
  86325. this._system.lensFlares.splice(index, 1);
  86326. };
  86327. ;
  86328. return LensFlare;
  86329. }());
  86330. BABYLON.LensFlare = LensFlare;
  86331. })(BABYLON || (BABYLON = {}));
  86332. //# sourceMappingURL=babylon.lensFlare.js.map
  86333. var BABYLON;
  86334. (function (BABYLON) {
  86335. // Adds the parser to the scene parsers.
  86336. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  86337. // Lens flares
  86338. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  86339. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  86340. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  86341. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  86342. container.lensFlareSystems.push(lf);
  86343. }
  86344. }
  86345. });
  86346. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  86347. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86348. if (this.lensFlareSystems[index].name === name) {
  86349. return this.lensFlareSystems[index];
  86350. }
  86351. }
  86352. return null;
  86353. };
  86354. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  86355. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  86356. if (this.lensFlareSystems[index].id === id) {
  86357. return this.lensFlareSystems[index];
  86358. }
  86359. }
  86360. return null;
  86361. };
  86362. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  86363. var index = this.lensFlareSystems.indexOf(toRemove);
  86364. if (index !== -1) {
  86365. this.lensFlareSystems.splice(index, 1);
  86366. }
  86367. return index;
  86368. };
  86369. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  86370. this.lensFlareSystems.push(newLensFlareSystem);
  86371. };
  86372. /**
  86373. * Defines the lens flare scene component responsible to manage any lens flares
  86374. * in a given scene.
  86375. */
  86376. var LensFlareSystemSceneComponent = /** @class */ (function () {
  86377. /**
  86378. * Creates a new instance of the component for the given scene
  86379. * @param scene Defines the scene to register the component in
  86380. */
  86381. function LensFlareSystemSceneComponent(scene) {
  86382. /**
  86383. * The component name helpfull to identify the component in the list of scene components.
  86384. */
  86385. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  86386. this.scene = scene;
  86387. scene.lensFlareSystems = new Array();
  86388. }
  86389. /**
  86390. * Registers the component in a given scene
  86391. */
  86392. LensFlareSystemSceneComponent.prototype.register = function () {
  86393. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  86394. };
  86395. /**
  86396. * Rebuilds the elements related to this component in case of
  86397. * context lost for instance.
  86398. */
  86399. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  86400. // Nothing to do for lens flare
  86401. };
  86402. /**
  86403. * Adds all the element from the container to the scene
  86404. * @param container the container holding the elements
  86405. */
  86406. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  86407. var _this = this;
  86408. if (!container.lensFlareSystems) {
  86409. return;
  86410. }
  86411. container.lensFlareSystems.forEach(function (o) {
  86412. _this.scene.addLensFlareSystem(o);
  86413. });
  86414. };
  86415. /**
  86416. * Removes all the elements in the container from the scene
  86417. * @param container contains the elements to remove
  86418. */
  86419. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  86420. var _this = this;
  86421. if (!container.lensFlareSystems) {
  86422. return;
  86423. }
  86424. container.lensFlareSystems.forEach(function (o) {
  86425. _this.scene.removeLensFlareSystem(o);
  86426. });
  86427. };
  86428. /**
  86429. * Serializes the component data to the specified json object
  86430. * @param serializationObject The object to serialize to
  86431. */
  86432. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  86433. // Lens flares
  86434. serializationObject.lensFlareSystems = [];
  86435. var lensFlareSystems = this.scene.lensFlareSystems;
  86436. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  86437. var lensFlareSystem = lensFlareSystems_1[_i];
  86438. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  86439. }
  86440. };
  86441. /**
  86442. * Disposes the component and the associated ressources.
  86443. */
  86444. LensFlareSystemSceneComponent.prototype.dispose = function () {
  86445. var lensFlareSystems = this.scene.lensFlareSystems;
  86446. while (lensFlareSystems.length) {
  86447. lensFlareSystems[0].dispose();
  86448. }
  86449. };
  86450. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  86451. // Lens flares
  86452. if (this.scene.lensFlaresEnabled) {
  86453. var lensFlareSystems = this.scene.lensFlareSystems;
  86454. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86455. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  86456. var lensFlareSystem = lensFlareSystems_2[_i];
  86457. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  86458. lensFlareSystem.render();
  86459. }
  86460. }
  86461. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  86462. }
  86463. };
  86464. return LensFlareSystemSceneComponent;
  86465. }());
  86466. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  86467. })(BABYLON || (BABYLON = {}));
  86468. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  86469. var BABYLON;
  86470. (function (BABYLON) {
  86471. var LensFlareSystem = /** @class */ (function () {
  86472. function LensFlareSystem(name, emitter, scene) {
  86473. this.name = name;
  86474. this.lensFlares = new Array();
  86475. this.borderLimit = 300;
  86476. this.viewportBorder = 0;
  86477. this.layerMask = 0x0FFFFFFF;
  86478. this._vertexBuffers = {};
  86479. this._isEnabled = true;
  86480. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86481. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  86482. if (!component) {
  86483. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  86484. scene._addComponent(component);
  86485. }
  86486. this._emitter = emitter;
  86487. this.id = name;
  86488. scene.lensFlareSystems.push(this);
  86489. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  86490. var engine = scene.getEngine();
  86491. // VBO
  86492. var vertices = [];
  86493. vertices.push(1, 1);
  86494. vertices.push(-1, 1);
  86495. vertices.push(-1, -1);
  86496. vertices.push(1, -1);
  86497. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86498. // Indices
  86499. var indices = [];
  86500. indices.push(0);
  86501. indices.push(1);
  86502. indices.push(2);
  86503. indices.push(0);
  86504. indices.push(2);
  86505. indices.push(3);
  86506. this._indexBuffer = engine.createIndexBuffer(indices);
  86507. // Effects
  86508. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  86509. }
  86510. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  86511. get: function () {
  86512. return this._isEnabled;
  86513. },
  86514. set: function (value) {
  86515. this._isEnabled = value;
  86516. },
  86517. enumerable: true,
  86518. configurable: true
  86519. });
  86520. LensFlareSystem.prototype.getScene = function () {
  86521. return this._scene;
  86522. };
  86523. LensFlareSystem.prototype.getEmitter = function () {
  86524. return this._emitter;
  86525. };
  86526. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  86527. this._emitter = newEmitter;
  86528. };
  86529. LensFlareSystem.prototype.getEmitterPosition = function () {
  86530. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  86531. };
  86532. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  86533. var position = this.getEmitterPosition();
  86534. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  86535. this._positionX = position.x;
  86536. this._positionY = position.y;
  86537. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  86538. if (this.viewportBorder > 0) {
  86539. globalViewport.x -= this.viewportBorder;
  86540. globalViewport.y -= this.viewportBorder;
  86541. globalViewport.width += this.viewportBorder * 2;
  86542. globalViewport.height += this.viewportBorder * 2;
  86543. position.x += this.viewportBorder;
  86544. position.y += this.viewportBorder;
  86545. this._positionX += this.viewportBorder;
  86546. this._positionY += this.viewportBorder;
  86547. }
  86548. if (position.z > 0) {
  86549. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  86550. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  86551. return true;
  86552. }
  86553. return true;
  86554. }
  86555. return false;
  86556. };
  86557. /** @hidden */
  86558. LensFlareSystem.prototype._isVisible = function () {
  86559. if (!this._isEnabled || !this._scene.activeCamera) {
  86560. return false;
  86561. }
  86562. var emitterPosition = this.getEmitterPosition();
  86563. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  86564. var distance = direction.length();
  86565. direction.normalize();
  86566. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  86567. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  86568. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  86569. };
  86570. LensFlareSystem.prototype.render = function () {
  86571. if (!this._effect.isReady() || !this._scene.activeCamera)
  86572. return false;
  86573. var engine = this._scene.getEngine();
  86574. var viewport = this._scene.activeCamera.viewport;
  86575. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  86576. // Position
  86577. if (!this.computeEffectivePosition(globalViewport)) {
  86578. return false;
  86579. }
  86580. // Visibility
  86581. if (!this._isVisible()) {
  86582. return false;
  86583. }
  86584. // Intensity
  86585. var awayX;
  86586. var awayY;
  86587. if (this._positionX < this.borderLimit + globalViewport.x) {
  86588. awayX = this.borderLimit + globalViewport.x - this._positionX;
  86589. }
  86590. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  86591. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  86592. }
  86593. else {
  86594. awayX = 0;
  86595. }
  86596. if (this._positionY < this.borderLimit + globalViewport.y) {
  86597. awayY = this.borderLimit + globalViewport.y - this._positionY;
  86598. }
  86599. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  86600. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  86601. }
  86602. else {
  86603. awayY = 0;
  86604. }
  86605. var away = (awayX > awayY) ? awayX : awayY;
  86606. away -= this.viewportBorder;
  86607. if (away > this.borderLimit) {
  86608. away = this.borderLimit;
  86609. }
  86610. var intensity = 1.0 - (away / this.borderLimit);
  86611. if (intensity < 0) {
  86612. return false;
  86613. }
  86614. if (intensity > 1.0) {
  86615. intensity = 1.0;
  86616. }
  86617. if (this.viewportBorder > 0) {
  86618. globalViewport.x += this.viewportBorder;
  86619. globalViewport.y += this.viewportBorder;
  86620. globalViewport.width -= this.viewportBorder * 2;
  86621. globalViewport.height -= this.viewportBorder * 2;
  86622. this._positionX -= this.viewportBorder;
  86623. this._positionY -= this.viewportBorder;
  86624. }
  86625. // Position
  86626. var centerX = globalViewport.x + globalViewport.width / 2;
  86627. var centerY = globalViewport.y + globalViewport.height / 2;
  86628. var distX = centerX - this._positionX;
  86629. var distY = centerY - this._positionY;
  86630. // Effects
  86631. engine.enableEffect(this._effect);
  86632. engine.setState(false);
  86633. engine.setDepthBuffer(false);
  86634. // VBOs
  86635. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  86636. // Flares
  86637. for (var index = 0; index < this.lensFlares.length; index++) {
  86638. var flare = this.lensFlares[index];
  86639. engine.setAlphaMode(flare.alphaMode);
  86640. var x = centerX - (distX * flare.position);
  86641. var y = centerY - (distY * flare.position);
  86642. var cw = flare.size;
  86643. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  86644. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  86645. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  86646. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  86647. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  86648. // Texture
  86649. this._effect.setTexture("textureSampler", flare.texture);
  86650. // Color
  86651. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  86652. // Draw order
  86653. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86654. }
  86655. engine.setDepthBuffer(true);
  86656. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86657. return true;
  86658. };
  86659. LensFlareSystem.prototype.dispose = function () {
  86660. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86661. if (vertexBuffer) {
  86662. vertexBuffer.dispose();
  86663. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86664. }
  86665. if (this._indexBuffer) {
  86666. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86667. this._indexBuffer = null;
  86668. }
  86669. while (this.lensFlares.length) {
  86670. this.lensFlares[0].dispose();
  86671. }
  86672. // Remove from scene
  86673. var index = this._scene.lensFlareSystems.indexOf(this);
  86674. this._scene.lensFlareSystems.splice(index, 1);
  86675. };
  86676. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  86677. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  86678. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  86679. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  86680. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  86681. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  86682. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  86683. var parsedFlare = parsedLensFlareSystem.flares[index];
  86684. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  86685. }
  86686. return lensFlareSystem;
  86687. };
  86688. LensFlareSystem.prototype.serialize = function () {
  86689. var serializationObject = {};
  86690. serializationObject.id = this.id;
  86691. serializationObject.name = this.name;
  86692. serializationObject.emitterId = this.getEmitter().id;
  86693. serializationObject.borderLimit = this.borderLimit;
  86694. serializationObject.flares = [];
  86695. for (var index = 0; index < this.lensFlares.length; index++) {
  86696. var flare = this.lensFlares[index];
  86697. serializationObject.flares.push({
  86698. size: flare.size,
  86699. position: flare.position,
  86700. color: flare.color.asArray(),
  86701. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  86702. });
  86703. }
  86704. return serializationObject;
  86705. };
  86706. return LensFlareSystem;
  86707. }());
  86708. BABYLON.LensFlareSystem = LensFlareSystem;
  86709. })(BABYLON || (BABYLON = {}));
  86710. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  86711. var BABYLON;
  86712. (function (BABYLON) {
  86713. /**
  86714. * This is a holder class for the physics joint created by the physics plugin.
  86715. * It holds a set of functions to control the underlying joint.
  86716. */
  86717. var PhysicsJoint = /** @class */ (function () {
  86718. function PhysicsJoint(type, jointData) {
  86719. this.type = type;
  86720. this.jointData = jointData;
  86721. jointData.nativeParams = jointData.nativeParams || {};
  86722. }
  86723. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  86724. get: function () {
  86725. return this._physicsJoint;
  86726. },
  86727. set: function (newJoint) {
  86728. if (this._physicsJoint) {
  86729. //remove from the wolrd
  86730. }
  86731. this._physicsJoint = newJoint;
  86732. },
  86733. enumerable: true,
  86734. configurable: true
  86735. });
  86736. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  86737. set: function (physicsPlugin) {
  86738. this._physicsPlugin = physicsPlugin;
  86739. },
  86740. enumerable: true,
  86741. configurable: true
  86742. });
  86743. /**
  86744. * Execute a function that is physics-plugin specific.
  86745. * @param {Function} func the function that will be executed.
  86746. * It accepts two parameters: the physics world and the physics joint.
  86747. */
  86748. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  86749. func(this._physicsPlugin.world, this._physicsJoint);
  86750. };
  86751. //TODO check if the native joints are the same
  86752. //Joint Types
  86753. PhysicsJoint.DistanceJoint = 0;
  86754. PhysicsJoint.HingeJoint = 1;
  86755. PhysicsJoint.BallAndSocketJoint = 2;
  86756. PhysicsJoint.WheelJoint = 3;
  86757. PhysicsJoint.SliderJoint = 4;
  86758. //OIMO
  86759. PhysicsJoint.PrismaticJoint = 5;
  86760. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  86761. PhysicsJoint.UniversalJoint = 6;
  86762. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  86763. //Cannon
  86764. //Similar to a Ball-Joint. Different in params
  86765. PhysicsJoint.PointToPointJoint = 8;
  86766. //Cannon only at the moment
  86767. PhysicsJoint.SpringJoint = 9;
  86768. PhysicsJoint.LockJoint = 10;
  86769. return PhysicsJoint;
  86770. }());
  86771. BABYLON.PhysicsJoint = PhysicsJoint;
  86772. /**
  86773. * A class representing a physics distance joint.
  86774. */
  86775. var DistanceJoint = /** @class */ (function (_super) {
  86776. __extends(DistanceJoint, _super);
  86777. function DistanceJoint(jointData) {
  86778. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  86779. }
  86780. /**
  86781. * Update the predefined distance.
  86782. */
  86783. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  86784. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  86785. };
  86786. return DistanceJoint;
  86787. }(PhysicsJoint));
  86788. BABYLON.DistanceJoint = DistanceJoint;
  86789. var MotorEnabledJoint = /** @class */ (function (_super) {
  86790. __extends(MotorEnabledJoint, _super);
  86791. function MotorEnabledJoint(type, jointData) {
  86792. return _super.call(this, type, jointData) || this;
  86793. }
  86794. /**
  86795. * Set the motor values.
  86796. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86797. * @param {number} force the force to apply
  86798. * @param {number} maxForce max force for this motor.
  86799. */
  86800. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  86801. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86802. };
  86803. /**
  86804. * Set the motor's limits.
  86805. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86806. */
  86807. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86808. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86809. };
  86810. return MotorEnabledJoint;
  86811. }(PhysicsJoint));
  86812. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  86813. /**
  86814. * This class represents a single hinge physics joint
  86815. */
  86816. var HingeJoint = /** @class */ (function (_super) {
  86817. __extends(HingeJoint, _super);
  86818. function HingeJoint(jointData) {
  86819. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  86820. }
  86821. /**
  86822. * Set the motor values.
  86823. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86824. * @param {number} force the force to apply
  86825. * @param {number} maxForce max force for this motor.
  86826. */
  86827. HingeJoint.prototype.setMotor = function (force, maxForce) {
  86828. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86829. };
  86830. /**
  86831. * Set the motor's limits.
  86832. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86833. */
  86834. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86835. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86836. };
  86837. return HingeJoint;
  86838. }(MotorEnabledJoint));
  86839. BABYLON.HingeJoint = HingeJoint;
  86840. /**
  86841. * This class represents a dual hinge physics joint (same as wheel joint)
  86842. */
  86843. var Hinge2Joint = /** @class */ (function (_super) {
  86844. __extends(Hinge2Joint, _super);
  86845. function Hinge2Joint(jointData) {
  86846. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  86847. }
  86848. /**
  86849. * Set the motor values.
  86850. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86851. * @param {number} force the force to apply
  86852. * @param {number} maxForce max force for this motor.
  86853. * @param {motorIndex} the motor's index, 0 or 1.
  86854. */
  86855. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  86856. if (motorIndex === void 0) { motorIndex = 0; }
  86857. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  86858. };
  86859. /**
  86860. * Set the motor limits.
  86861. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86862. * @param {number} upperLimit the upper limit
  86863. * @param {number} lowerLimit lower limit
  86864. * @param {motorIndex} the motor's index, 0 or 1.
  86865. */
  86866. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  86867. if (motorIndex === void 0) { motorIndex = 0; }
  86868. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  86869. };
  86870. return Hinge2Joint;
  86871. }(MotorEnabledJoint));
  86872. BABYLON.Hinge2Joint = Hinge2Joint;
  86873. })(BABYLON || (BABYLON = {}));
  86874. //# sourceMappingURL=babylon.physicsJoint.js.map
  86875. var BABYLON;
  86876. (function (BABYLON) {
  86877. var PhysicsImpostor = /** @class */ (function () {
  86878. function PhysicsImpostor(object, type, _options, _scene) {
  86879. if (_options === void 0) { _options = { mass: 0 }; }
  86880. var _this = this;
  86881. this.object = object;
  86882. this.type = type;
  86883. this._options = _options;
  86884. this._scene = _scene;
  86885. this._bodyUpdateRequired = false;
  86886. this._onBeforePhysicsStepCallbacks = new Array();
  86887. this._onAfterPhysicsStepCallbacks = new Array();
  86888. this._onPhysicsCollideCallbacks = [];
  86889. this._deltaPosition = BABYLON.Vector3.Zero();
  86890. this._isDisposed = false;
  86891. //temp variables for parent rotation calculations
  86892. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  86893. this._tmpQuat = new BABYLON.Quaternion();
  86894. this._tmpQuat2 = new BABYLON.Quaternion();
  86895. /**
  86896. * this function is executed by the physics engine.
  86897. */
  86898. this.beforeStep = function () {
  86899. if (!_this._physicsEngine) {
  86900. return;
  86901. }
  86902. _this.object.translate(_this._deltaPosition, -1);
  86903. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  86904. _this.object.computeWorldMatrix(false);
  86905. if (_this.object.parent && _this.object.rotationQuaternion) {
  86906. _this.getParentsRotation();
  86907. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  86908. }
  86909. else {
  86910. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  86911. }
  86912. if (!_this._options.disableBidirectionalTransformation) {
  86913. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  86914. }
  86915. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  86916. func(_this);
  86917. });
  86918. };
  86919. /**
  86920. * this function is executed by the physics engine.
  86921. */
  86922. this.afterStep = function () {
  86923. if (!_this._physicsEngine) {
  86924. return;
  86925. }
  86926. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  86927. func(_this);
  86928. });
  86929. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  86930. // object has now its world rotation. needs to be converted to local.
  86931. if (_this.object.parent && _this.object.rotationQuaternion) {
  86932. _this.getParentsRotation();
  86933. _this._tmpQuat.conjugateInPlace();
  86934. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  86935. }
  86936. // take the position set and make it the absolute position of this object.
  86937. _this.object.setAbsolutePosition(_this.object.position);
  86938. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  86939. _this.object.translate(_this._deltaPosition, 1);
  86940. };
  86941. /**
  86942. * Legacy collision detection event support
  86943. */
  86944. this.onCollideEvent = null;
  86945. //event and body object due to cannon's event-based architecture.
  86946. this.onCollide = function (e) {
  86947. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  86948. return;
  86949. }
  86950. if (!_this._physicsEngine) {
  86951. return;
  86952. }
  86953. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  86954. if (otherImpostor) {
  86955. // Legacy collision detection event support
  86956. if (_this.onCollideEvent) {
  86957. _this.onCollideEvent(_this, otherImpostor);
  86958. }
  86959. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  86960. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  86961. }).forEach(function (obj) {
  86962. obj.callback(_this, otherImpostor);
  86963. });
  86964. }
  86965. };
  86966. //sanity check!
  86967. if (!this.object) {
  86968. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  86969. return;
  86970. }
  86971. //legacy support for old syntax.
  86972. if (!this._scene && object.getScene) {
  86973. this._scene = object.getScene();
  86974. }
  86975. if (!this._scene) {
  86976. return;
  86977. }
  86978. this._physicsEngine = this._scene.getPhysicsEngine();
  86979. if (!this._physicsEngine) {
  86980. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  86981. }
  86982. else {
  86983. //set the object's quaternion, if not set
  86984. if (!this.object.rotationQuaternion) {
  86985. if (this.object.rotation) {
  86986. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  86987. }
  86988. else {
  86989. this.object.rotationQuaternion = new BABYLON.Quaternion();
  86990. }
  86991. }
  86992. //default options params
  86993. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  86994. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  86995. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  86996. this._joints = [];
  86997. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  86998. if (!this.object.parent || this._options.ignoreParent) {
  86999. this._init();
  87000. }
  87001. else if (this.object.parent.physicsImpostor) {
  87002. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  87003. }
  87004. }
  87005. }
  87006. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  87007. get: function () {
  87008. return this._isDisposed;
  87009. },
  87010. enumerable: true,
  87011. configurable: true
  87012. });
  87013. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  87014. get: function () {
  87015. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  87016. },
  87017. set: function (value) {
  87018. this.setMass(value);
  87019. },
  87020. enumerable: true,
  87021. configurable: true
  87022. });
  87023. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  87024. get: function () {
  87025. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  87026. },
  87027. set: function (value) {
  87028. if (!this._physicsEngine) {
  87029. return;
  87030. }
  87031. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  87032. },
  87033. enumerable: true,
  87034. configurable: true
  87035. });
  87036. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  87037. get: function () {
  87038. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  87039. },
  87040. set: function (value) {
  87041. if (!this._physicsEngine) {
  87042. return;
  87043. }
  87044. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  87045. },
  87046. enumerable: true,
  87047. configurable: true
  87048. });
  87049. /**
  87050. * This function will completly initialize this impostor.
  87051. * It will create a new body - but only if this mesh has no parent.
  87052. * If it has, this impostor will not be used other than to define the impostor
  87053. * of the child mesh.
  87054. * @hidden
  87055. */
  87056. PhysicsImpostor.prototype._init = function () {
  87057. if (!this._physicsEngine) {
  87058. return;
  87059. }
  87060. this._physicsEngine.removeImpostor(this);
  87061. this.physicsBody = null;
  87062. this._parent = this._parent || this._getPhysicsParent();
  87063. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  87064. this._physicsEngine.addImpostor(this);
  87065. }
  87066. };
  87067. PhysicsImpostor.prototype._getPhysicsParent = function () {
  87068. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  87069. var parentMesh = this.object.parent;
  87070. return parentMesh.physicsImpostor;
  87071. }
  87072. return null;
  87073. };
  87074. /**
  87075. * Should a new body be generated.
  87076. */
  87077. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  87078. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  87079. };
  87080. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  87081. this.forceUpdate();
  87082. };
  87083. /**
  87084. * Force a regeneration of this or the parent's impostor's body.
  87085. * Use under cautious - This will remove all joints already implemented.
  87086. */
  87087. PhysicsImpostor.prototype.forceUpdate = function () {
  87088. this._init();
  87089. if (this.parent && !this._options.ignoreParent) {
  87090. this.parent.forceUpdate();
  87091. }
  87092. };
  87093. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  87094. /*public get mesh(): AbstractMesh {
  87095. return this._mesh;
  87096. }*/
  87097. /**
  87098. * Gets the body that holds this impostor. Either its own, or its parent.
  87099. */
  87100. get: function () {
  87101. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  87102. },
  87103. /**
  87104. * Set the physics body. Used mainly by the physics engine/plugin
  87105. */
  87106. set: function (physicsBody) {
  87107. if (this._physicsBody && this._physicsEngine) {
  87108. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  87109. }
  87110. this._physicsBody = physicsBody;
  87111. this.resetUpdateFlags();
  87112. },
  87113. enumerable: true,
  87114. configurable: true
  87115. });
  87116. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  87117. get: function () {
  87118. return !this._options.ignoreParent && this._parent ? this._parent : null;
  87119. },
  87120. set: function (value) {
  87121. this._parent = value;
  87122. },
  87123. enumerable: true,
  87124. configurable: true
  87125. });
  87126. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  87127. this._bodyUpdateRequired = false;
  87128. };
  87129. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  87130. if (this.object.getBoundingInfo) {
  87131. var q = this.object.rotationQuaternion;
  87132. //reset rotation
  87133. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  87134. //calculate the world matrix with no rotation
  87135. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87136. var boundingInfo = this.object.getBoundingInfo();
  87137. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  87138. //bring back the rotation
  87139. this.object.rotationQuaternion = q;
  87140. //calculate the world matrix with the new rotation
  87141. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  87142. return size;
  87143. }
  87144. else {
  87145. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  87146. }
  87147. };
  87148. PhysicsImpostor.prototype.getObjectCenter = function () {
  87149. if (this.object.getBoundingInfo) {
  87150. var boundingInfo = this.object.getBoundingInfo();
  87151. return boundingInfo.boundingBox.centerWorld;
  87152. }
  87153. else {
  87154. return this.object.position;
  87155. }
  87156. };
  87157. /**
  87158. * Get a specific parametes from the options parameter.
  87159. */
  87160. PhysicsImpostor.prototype.getParam = function (paramName) {
  87161. return this._options[paramName];
  87162. };
  87163. /**
  87164. * Sets a specific parameter in the options given to the physics plugin
  87165. */
  87166. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  87167. this._options[paramName] = value;
  87168. this._bodyUpdateRequired = true;
  87169. };
  87170. /**
  87171. * Specifically change the body's mass option. Won't recreate the physics body object
  87172. */
  87173. PhysicsImpostor.prototype.setMass = function (mass) {
  87174. if (this.getParam("mass") !== mass) {
  87175. this.setParam("mass", mass);
  87176. }
  87177. if (this._physicsEngine) {
  87178. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  87179. }
  87180. };
  87181. PhysicsImpostor.prototype.getLinearVelocity = function () {
  87182. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  87183. };
  87184. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  87185. if (this._physicsEngine) {
  87186. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  87187. }
  87188. };
  87189. PhysicsImpostor.prototype.getAngularVelocity = function () {
  87190. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  87191. };
  87192. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  87193. if (this._physicsEngine) {
  87194. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  87195. }
  87196. };
  87197. /**
  87198. * Execute a function with the physics plugin native code.
  87199. * Provide a function the will have two variables - the world object and the physics body object.
  87200. */
  87201. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  87202. if (this._physicsEngine) {
  87203. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  87204. }
  87205. };
  87206. /**
  87207. * Register a function that will be executed before the physics world is stepping forward.
  87208. */
  87209. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  87210. this._onBeforePhysicsStepCallbacks.push(func);
  87211. };
  87212. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  87213. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  87214. if (index > -1) {
  87215. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  87216. }
  87217. else {
  87218. BABYLON.Tools.Warn("Function to remove was not found");
  87219. }
  87220. };
  87221. /**
  87222. * Register a function that will be executed after the physics step
  87223. */
  87224. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  87225. this._onAfterPhysicsStepCallbacks.push(func);
  87226. };
  87227. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  87228. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  87229. if (index > -1) {
  87230. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  87231. }
  87232. else {
  87233. BABYLON.Tools.Warn("Function to remove was not found");
  87234. }
  87235. };
  87236. /**
  87237. * register a function that will be executed when this impostor collides against a different body.
  87238. */
  87239. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  87240. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87241. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  87242. };
  87243. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  87244. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  87245. var index = -1;
  87246. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  87247. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  87248. // chcek the arrays match
  87249. var sameList = cbDef.otherImpostors.every(function (impostor) {
  87250. return collidedAgainstList.indexOf(impostor) > -1;
  87251. });
  87252. if (sameList) {
  87253. index = idx;
  87254. }
  87255. return sameList;
  87256. }
  87257. return false;
  87258. });
  87259. if (found) {
  87260. this._onPhysicsCollideCallbacks.splice(index, 1);
  87261. }
  87262. else {
  87263. BABYLON.Tools.Warn("Function to remove was not found");
  87264. }
  87265. };
  87266. PhysicsImpostor.prototype.getParentsRotation = function () {
  87267. var parent = this.object.parent;
  87268. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  87269. while (parent) {
  87270. if (parent.rotationQuaternion) {
  87271. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  87272. }
  87273. else {
  87274. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  87275. }
  87276. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  87277. parent = parent.parent;
  87278. }
  87279. return this._tmpQuat;
  87280. };
  87281. /**
  87282. * Apply a force
  87283. */
  87284. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  87285. if (this._physicsEngine) {
  87286. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  87287. }
  87288. return this;
  87289. };
  87290. /**
  87291. * Apply an impulse
  87292. */
  87293. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  87294. if (this._physicsEngine) {
  87295. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  87296. }
  87297. return this;
  87298. };
  87299. /**
  87300. * A help function to create a joint.
  87301. */
  87302. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  87303. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  87304. this.addJoint(otherImpostor, joint);
  87305. return this;
  87306. };
  87307. /**
  87308. * Add a joint to this impostor with a different impostor.
  87309. */
  87310. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  87311. this._joints.push({
  87312. otherImpostor: otherImpostor,
  87313. joint: joint
  87314. });
  87315. if (this._physicsEngine) {
  87316. this._physicsEngine.addJoint(this, otherImpostor, joint);
  87317. }
  87318. return this;
  87319. };
  87320. /**
  87321. * Will keep this body still, in a sleep mode.
  87322. */
  87323. PhysicsImpostor.prototype.sleep = function () {
  87324. if (this._physicsEngine) {
  87325. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  87326. }
  87327. return this;
  87328. };
  87329. /**
  87330. * Wake the body up.
  87331. */
  87332. PhysicsImpostor.prototype.wakeUp = function () {
  87333. if (this._physicsEngine) {
  87334. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  87335. }
  87336. return this;
  87337. };
  87338. PhysicsImpostor.prototype.clone = function (newObject) {
  87339. if (!newObject)
  87340. return null;
  87341. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  87342. };
  87343. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  87344. var _this = this;
  87345. //no dispose if no physics engine is available.
  87346. if (!this._physicsEngine) {
  87347. return;
  87348. }
  87349. this._joints.forEach(function (j) {
  87350. if (_this._physicsEngine) {
  87351. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  87352. }
  87353. });
  87354. //dispose the physics body
  87355. this._physicsEngine.removeImpostor(this);
  87356. if (this.parent) {
  87357. this.parent.forceUpdate();
  87358. }
  87359. else {
  87360. /*this._object.getChildMeshes().forEach(function(mesh) {
  87361. if (mesh.physicsImpostor) {
  87362. if (disposeChildren) {
  87363. mesh.physicsImpostor.dispose();
  87364. mesh.physicsImpostor = null;
  87365. }
  87366. }
  87367. })*/
  87368. }
  87369. this._isDisposed = true;
  87370. };
  87371. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  87372. this._deltaPosition.copyFrom(position);
  87373. };
  87374. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  87375. if (!this._deltaRotation) {
  87376. this._deltaRotation = new BABYLON.Quaternion();
  87377. }
  87378. this._deltaRotation.copyFrom(rotation);
  87379. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  87380. };
  87381. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  87382. if (this._physicsEngine) {
  87383. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  87384. }
  87385. return this;
  87386. };
  87387. PhysicsImpostor.prototype.getRadius = function () {
  87388. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  87389. };
  87390. /**
  87391. * Sync a bone with this impostor
  87392. * @param bone The bone to sync to the impostor.
  87393. * @param boneMesh The mesh that the bone is influencing.
  87394. * @param jointPivot The pivot of the joint / bone in local space.
  87395. * @param distToJoint Optional distance from the impostor to the joint.
  87396. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87397. */
  87398. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  87399. var tempVec = PhysicsImpostor._tmpVecs[0];
  87400. var mesh = this.object;
  87401. if (mesh.rotationQuaternion) {
  87402. if (adjustRotation) {
  87403. var tempQuat = PhysicsImpostor._tmpQuat;
  87404. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  87405. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  87406. }
  87407. else {
  87408. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  87409. }
  87410. }
  87411. tempVec.x = 0;
  87412. tempVec.y = 0;
  87413. tempVec.z = 0;
  87414. if (jointPivot) {
  87415. tempVec.x = jointPivot.x;
  87416. tempVec.y = jointPivot.y;
  87417. tempVec.z = jointPivot.z;
  87418. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  87419. if (distToJoint === undefined || distToJoint === null) {
  87420. distToJoint = jointPivot.length();
  87421. }
  87422. tempVec.x *= distToJoint;
  87423. tempVec.y *= distToJoint;
  87424. tempVec.z *= distToJoint;
  87425. }
  87426. if (bone.getParent()) {
  87427. tempVec.addInPlace(mesh.getAbsolutePosition());
  87428. bone.setAbsolutePosition(tempVec, boneMesh);
  87429. }
  87430. else {
  87431. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  87432. boneMesh.position.x -= tempVec.x;
  87433. boneMesh.position.y -= tempVec.y;
  87434. boneMesh.position.z -= tempVec.z;
  87435. }
  87436. };
  87437. /**
  87438. * Sync impostor to a bone
  87439. * @param bone The bone that the impostor will be synced to.
  87440. * @param boneMesh The mesh that the bone is influencing.
  87441. * @param jointPivot The pivot of the joint / bone in local space.
  87442. * @param distToJoint Optional distance from the impostor to the joint.
  87443. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  87444. * @param boneAxis Optional vector3 axis the bone is aligned with
  87445. */
  87446. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  87447. var mesh = this.object;
  87448. if (mesh.rotationQuaternion) {
  87449. if (adjustRotation) {
  87450. var tempQuat = PhysicsImpostor._tmpQuat;
  87451. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  87452. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  87453. }
  87454. else {
  87455. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  87456. }
  87457. }
  87458. var pos = PhysicsImpostor._tmpVecs[0];
  87459. var boneDir = PhysicsImpostor._tmpVecs[1];
  87460. if (!boneAxis) {
  87461. boneAxis = PhysicsImpostor._tmpVecs[2];
  87462. boneAxis.x = 0;
  87463. boneAxis.y = 1;
  87464. boneAxis.z = 0;
  87465. }
  87466. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  87467. bone.getAbsolutePositionToRef(boneMesh, pos);
  87468. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  87469. distToJoint = jointPivot.length();
  87470. }
  87471. if (distToJoint !== undefined && distToJoint !== null) {
  87472. pos.x += boneDir.x * distToJoint;
  87473. pos.y += boneDir.y * distToJoint;
  87474. pos.z += boneDir.z * distToJoint;
  87475. }
  87476. mesh.setAbsolutePosition(pos);
  87477. };
  87478. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  87479. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  87480. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87481. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  87482. //Impostor types
  87483. PhysicsImpostor.NoImpostor = 0;
  87484. PhysicsImpostor.SphereImpostor = 1;
  87485. PhysicsImpostor.BoxImpostor = 2;
  87486. PhysicsImpostor.PlaneImpostor = 3;
  87487. PhysicsImpostor.MeshImpostor = 4;
  87488. PhysicsImpostor.CylinderImpostor = 7;
  87489. PhysicsImpostor.ParticleImpostor = 8;
  87490. PhysicsImpostor.HeightmapImpostor = 9;
  87491. return PhysicsImpostor;
  87492. }());
  87493. BABYLON.PhysicsImpostor = PhysicsImpostor;
  87494. })(BABYLON || (BABYLON = {}));
  87495. //# sourceMappingURL=babylon.physicsImpostor.js.map
  87496. var BABYLON;
  87497. (function (BABYLON) {
  87498. var PhysicsEngine = /** @class */ (function () {
  87499. function PhysicsEngine(gravity, _physicsPlugin) {
  87500. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  87501. this._physicsPlugin = _physicsPlugin;
  87502. //new methods and parameters
  87503. this._impostors = [];
  87504. this._joints = [];
  87505. if (!this._physicsPlugin.isSupported()) {
  87506. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  87507. + "Please make sure it is included.");
  87508. }
  87509. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  87510. this.setGravity(gravity);
  87511. this.setTimeStep();
  87512. }
  87513. PhysicsEngine.prototype.setGravity = function (gravity) {
  87514. this.gravity = gravity;
  87515. this._physicsPlugin.setGravity(this.gravity);
  87516. };
  87517. /**
  87518. * Set the time step of the physics engine.
  87519. * default is 1/60.
  87520. * To slow it down, enter 1/600 for example.
  87521. * To speed it up, 1/30
  87522. * @param {number} newTimeStep the new timestep to apply to this world.
  87523. */
  87524. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  87525. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  87526. this._physicsPlugin.setTimeStep(newTimeStep);
  87527. };
  87528. /**
  87529. * Get the time step of the physics engine.
  87530. */
  87531. PhysicsEngine.prototype.getTimeStep = function () {
  87532. return this._physicsPlugin.getTimeStep();
  87533. };
  87534. PhysicsEngine.prototype.dispose = function () {
  87535. this._impostors.forEach(function (impostor) {
  87536. impostor.dispose();
  87537. });
  87538. this._physicsPlugin.dispose();
  87539. };
  87540. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  87541. return this._physicsPlugin.name;
  87542. };
  87543. /**
  87544. * Adding a new impostor for the impostor tracking.
  87545. * This will be done by the impostor itself.
  87546. * @param {PhysicsImpostor} impostor the impostor to add
  87547. */
  87548. PhysicsEngine.prototype.addImpostor = function (impostor) {
  87549. impostor.uniqueId = this._impostors.push(impostor);
  87550. //if no parent, generate the body
  87551. if (!impostor.parent) {
  87552. this._physicsPlugin.generatePhysicsBody(impostor);
  87553. }
  87554. };
  87555. /**
  87556. * Remove an impostor from the engine.
  87557. * This impostor and its mesh will not longer be updated by the physics engine.
  87558. * @param {PhysicsImpostor} impostor the impostor to remove
  87559. */
  87560. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  87561. var index = this._impostors.indexOf(impostor);
  87562. if (index > -1) {
  87563. var removed = this._impostors.splice(index, 1);
  87564. //Is it needed?
  87565. if (removed.length) {
  87566. //this will also remove it from the world.
  87567. removed[0].physicsBody = null;
  87568. }
  87569. }
  87570. };
  87571. /**
  87572. * Add a joint to the physics engine
  87573. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  87574. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  87575. * @param {PhysicsJoint} the joint that will connect both impostors.
  87576. */
  87577. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  87578. var impostorJoint = {
  87579. mainImpostor: mainImpostor,
  87580. connectedImpostor: connectedImpostor,
  87581. joint: joint
  87582. };
  87583. joint.physicsPlugin = this._physicsPlugin;
  87584. this._joints.push(impostorJoint);
  87585. this._physicsPlugin.generateJoint(impostorJoint);
  87586. };
  87587. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  87588. var matchingJoints = this._joints.filter(function (impostorJoint) {
  87589. return (impostorJoint.connectedImpostor === connectedImpostor
  87590. && impostorJoint.joint === joint
  87591. && impostorJoint.mainImpostor === mainImpostor);
  87592. });
  87593. if (matchingJoints.length) {
  87594. this._physicsPlugin.removeJoint(matchingJoints[0]);
  87595. //TODO remove it from the list as well
  87596. }
  87597. };
  87598. /**
  87599. * Called by the scene. no need to call it.
  87600. * @hidden
  87601. */
  87602. PhysicsEngine.prototype._step = function (delta) {
  87603. var _this = this;
  87604. //check if any mesh has no body / requires an update
  87605. this._impostors.forEach(function (impostor) {
  87606. if (impostor.isBodyInitRequired()) {
  87607. _this._physicsPlugin.generatePhysicsBody(impostor);
  87608. }
  87609. });
  87610. if (delta > 0.1) {
  87611. delta = 0.1;
  87612. }
  87613. else if (delta <= 0) {
  87614. delta = 1.0 / 60.0;
  87615. }
  87616. this._physicsPlugin.executeStep(delta, this._impostors);
  87617. };
  87618. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  87619. return this._physicsPlugin;
  87620. };
  87621. PhysicsEngine.prototype.getImpostors = function () {
  87622. return this._impostors;
  87623. };
  87624. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  87625. for (var i = 0; i < this._impostors.length; ++i) {
  87626. if (this._impostors[i].object === object) {
  87627. return this._impostors[i];
  87628. }
  87629. }
  87630. return null;
  87631. };
  87632. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  87633. for (var i = 0; i < this._impostors.length; ++i) {
  87634. if (this._impostors[i].physicsBody === body) {
  87635. return this._impostors[i];
  87636. }
  87637. }
  87638. return null;
  87639. };
  87640. // Statics
  87641. PhysicsEngine.Epsilon = 0.001;
  87642. return PhysicsEngine;
  87643. }());
  87644. BABYLON.PhysicsEngine = PhysicsEngine;
  87645. })(BABYLON || (BABYLON = {}));
  87646. //# sourceMappingURL=babylon.physicsEngine.js.map
  87647. var BABYLON;
  87648. (function (BABYLON) {
  87649. var PhysicsHelper = /** @class */ (function () {
  87650. function PhysicsHelper(scene) {
  87651. this._scene = scene;
  87652. this._physicsEngine = this._scene.getPhysicsEngine();
  87653. if (!this._physicsEngine) {
  87654. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  87655. }
  87656. }
  87657. /**
  87658. * @param {Vector3} origin the origin of the explosion
  87659. * @param {number} radius the explosion radius
  87660. * @param {number} strength the explosion strength
  87661. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87662. */
  87663. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  87664. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87665. if (!this._physicsEngine) {
  87666. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  87667. return null;
  87668. }
  87669. var impostors = this._physicsEngine.getImpostors();
  87670. if (impostors.length === 0) {
  87671. return null;
  87672. }
  87673. var event = new PhysicsRadialExplosionEvent(this._scene);
  87674. impostors.forEach(function (impostor) {
  87675. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87676. if (!impostorForceAndContactPoint) {
  87677. return;
  87678. }
  87679. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87680. });
  87681. event.dispose(false);
  87682. return event;
  87683. };
  87684. /**
  87685. * @param {Vector3} origin the origin of the explosion
  87686. * @param {number} radius the explosion radius
  87687. * @param {number} strength the explosion strength
  87688. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87689. */
  87690. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  87691. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87692. if (!this._physicsEngine) {
  87693. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87694. return null;
  87695. }
  87696. var impostors = this._physicsEngine.getImpostors();
  87697. if (impostors.length === 0) {
  87698. return null;
  87699. }
  87700. var event = new PhysicsRadialExplosionEvent(this._scene);
  87701. impostors.forEach(function (impostor) {
  87702. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87703. if (!impostorForceAndContactPoint) {
  87704. return;
  87705. }
  87706. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87707. });
  87708. event.dispose(false);
  87709. return event;
  87710. };
  87711. /**
  87712. * @param {Vector3} origin the origin of the explosion
  87713. * @param {number} radius the explosion radius
  87714. * @param {number} strength the explosion strength
  87715. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87716. */
  87717. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  87718. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87719. if (!this._physicsEngine) {
  87720. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87721. return null;
  87722. }
  87723. var impostors = this._physicsEngine.getImpostors();
  87724. if (impostors.length === 0) {
  87725. return null;
  87726. }
  87727. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  87728. event.dispose(false);
  87729. return event;
  87730. };
  87731. /**
  87732. * @param {Vector3} origin the origin of the updraft
  87733. * @param {number} radius the radius of the updraft
  87734. * @param {number} strength the strength of the updraft
  87735. * @param {number} height the height of the updraft
  87736. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  87737. */
  87738. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  87739. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  87740. if (!this._physicsEngine) {
  87741. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87742. return null;
  87743. }
  87744. if (this._physicsEngine.getImpostors().length === 0) {
  87745. return null;
  87746. }
  87747. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  87748. event.dispose(false);
  87749. return event;
  87750. };
  87751. /**
  87752. * @param {Vector3} origin the of the vortex
  87753. * @param {number} radius the radius of the vortex
  87754. * @param {number} strength the strength of the vortex
  87755. * @param {number} height the height of the vortex
  87756. */
  87757. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  87758. if (!this._physicsEngine) {
  87759. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87760. return null;
  87761. }
  87762. if (this._physicsEngine.getImpostors().length === 0) {
  87763. return null;
  87764. }
  87765. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  87766. event.dispose(false);
  87767. return event;
  87768. };
  87769. return PhysicsHelper;
  87770. }());
  87771. BABYLON.PhysicsHelper = PhysicsHelper;
  87772. /***** Radial explosion *****/
  87773. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  87774. function PhysicsRadialExplosionEvent(scene) {
  87775. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  87776. this._rays = [];
  87777. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  87778. this._scene = scene;
  87779. }
  87780. /**
  87781. * Returns the data related to the radial explosion event (sphere & rays).
  87782. * @returns {PhysicsRadialExplosionEventData}
  87783. */
  87784. PhysicsRadialExplosionEvent.prototype.getData = function () {
  87785. this._dataFetched = true;
  87786. return {
  87787. sphere: this._sphere,
  87788. rays: this._rays,
  87789. };
  87790. };
  87791. /**
  87792. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  87793. * @param impostor
  87794. * @param {Vector3} origin the origin of the explosion
  87795. * @param {number} radius the explosion radius
  87796. * @param {number} strength the explosion strength
  87797. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  87798. * @returns {Nullable<PhysicsForceAndContactPoint>}
  87799. */
  87800. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  87801. if (impostor.mass === 0) {
  87802. return null;
  87803. }
  87804. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  87805. return null;
  87806. }
  87807. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87808. return null;
  87809. }
  87810. var impostorObjectCenter = impostor.getObjectCenter();
  87811. var direction = impostorObjectCenter.subtract(origin);
  87812. var ray = new BABYLON.Ray(origin, direction, radius);
  87813. this._rays.push(ray);
  87814. var hit = ray.intersectsMesh(impostor.object);
  87815. var contactPoint = hit.pickedPoint;
  87816. if (!contactPoint) {
  87817. return null;
  87818. }
  87819. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  87820. if (distanceFromOrigin > radius) {
  87821. return null;
  87822. }
  87823. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  87824. ? strength
  87825. : strength * (1 - (distanceFromOrigin / radius));
  87826. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87827. return { force: force, contactPoint: contactPoint };
  87828. };
  87829. /**
  87830. * Disposes the sphere.
  87831. * @param {bolean} force
  87832. */
  87833. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  87834. var _this = this;
  87835. if (force === void 0) { force = true; }
  87836. if (force) {
  87837. this._sphere.dispose();
  87838. }
  87839. else {
  87840. setTimeout(function () {
  87841. if (!_this._dataFetched) {
  87842. _this._sphere.dispose();
  87843. }
  87844. }, 0);
  87845. }
  87846. };
  87847. /*** Helpers ***/
  87848. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  87849. if (!this._sphere) {
  87850. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  87851. this._sphere.isVisible = false;
  87852. }
  87853. };
  87854. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  87855. var impostorObject = impostor.object;
  87856. this._prepareSphere();
  87857. this._sphere.position = origin;
  87858. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  87859. this._sphere._updateBoundingInfo();
  87860. this._sphere.computeWorldMatrix(true);
  87861. return this._sphere.intersectsMesh(impostorObject, true);
  87862. };
  87863. return PhysicsRadialExplosionEvent;
  87864. }());
  87865. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  87866. /***** Gravitational Field *****/
  87867. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  87868. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  87869. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87870. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87871. this._physicsHelper = physicsHelper;
  87872. this._scene = scene;
  87873. this._origin = origin;
  87874. this._radius = radius;
  87875. this._strength = strength;
  87876. this._falloff = falloff;
  87877. this._tickCallback = this._tick.bind(this);
  87878. }
  87879. /**
  87880. * Returns the data related to the gravitational field event (sphere).
  87881. * @returns {PhysicsGravitationalFieldEventData}
  87882. */
  87883. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  87884. this._dataFetched = true;
  87885. return {
  87886. sphere: this._sphere,
  87887. };
  87888. };
  87889. /**
  87890. * Enables the gravitational field.
  87891. */
  87892. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  87893. this._tickCallback.call(this);
  87894. this._scene.registerBeforeRender(this._tickCallback);
  87895. };
  87896. /**
  87897. * Disables the gravitational field.
  87898. */
  87899. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  87900. this._scene.unregisterBeforeRender(this._tickCallback);
  87901. };
  87902. /**
  87903. * Disposes the sphere.
  87904. * @param {bolean} force
  87905. */
  87906. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  87907. var _this = this;
  87908. if (force === void 0) { force = true; }
  87909. if (force) {
  87910. this._sphere.dispose();
  87911. }
  87912. else {
  87913. setTimeout(function () {
  87914. if (!_this._dataFetched) {
  87915. _this._sphere.dispose();
  87916. }
  87917. }, 0);
  87918. }
  87919. };
  87920. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  87921. // Since the params won't change, we fetch the event only once
  87922. if (this._sphere) {
  87923. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87924. }
  87925. else {
  87926. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87927. if (radialExplosionEvent) {
  87928. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  87929. }
  87930. }
  87931. };
  87932. return PhysicsGravitationalFieldEvent;
  87933. }());
  87934. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  87935. /***** Updraft *****/
  87936. var PhysicsUpdraftEvent = /** @class */ (function () {
  87937. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  87938. this._scene = _scene;
  87939. this._origin = _origin;
  87940. this._radius = _radius;
  87941. this._strength = _strength;
  87942. this._height = _height;
  87943. this._updraftMode = _updraftMode;
  87944. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87945. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  87946. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87947. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87948. this._physicsEngine = this._scene.getPhysicsEngine();
  87949. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87950. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87951. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87952. this._originDirection = this._origin.subtract(this._originTop).normalize();
  87953. }
  87954. this._tickCallback = this._tick.bind(this);
  87955. }
  87956. /**
  87957. * Returns the data related to the updraft event (cylinder).
  87958. * @returns {PhysicsUpdraftEventData}
  87959. */
  87960. PhysicsUpdraftEvent.prototype.getData = function () {
  87961. this._dataFetched = true;
  87962. return {
  87963. cylinder: this._cylinder,
  87964. };
  87965. };
  87966. /**
  87967. * Enables the updraft.
  87968. */
  87969. PhysicsUpdraftEvent.prototype.enable = function () {
  87970. this._tickCallback.call(this);
  87971. this._scene.registerBeforeRender(this._tickCallback);
  87972. };
  87973. /**
  87974. * Disables the cortex.
  87975. */
  87976. PhysicsUpdraftEvent.prototype.disable = function () {
  87977. this._scene.unregisterBeforeRender(this._tickCallback);
  87978. };
  87979. /**
  87980. * Disposes the sphere.
  87981. * @param {bolean} force
  87982. */
  87983. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  87984. var _this = this;
  87985. if (force === void 0) { force = true; }
  87986. if (force) {
  87987. this._cylinder.dispose();
  87988. }
  87989. else {
  87990. setTimeout(function () {
  87991. if (!_this._dataFetched) {
  87992. _this._cylinder.dispose();
  87993. }
  87994. }, 0);
  87995. }
  87996. };
  87997. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87998. if (impostor.mass === 0) {
  87999. return null;
  88000. }
  88001. if (!this._intersectsWithCylinder(impostor)) {
  88002. return null;
  88003. }
  88004. var impostorObjectCenter = impostor.getObjectCenter();
  88005. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  88006. var direction = this._originDirection;
  88007. }
  88008. else {
  88009. var direction = impostorObjectCenter.subtract(this._originTop);
  88010. }
  88011. var multiplier = this._strength * -1;
  88012. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  88013. return { force: force, contactPoint: impostorObjectCenter };
  88014. };
  88015. PhysicsUpdraftEvent.prototype._tick = function () {
  88016. var _this = this;
  88017. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88018. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88019. if (!impostorForceAndContactPoint) {
  88020. return;
  88021. }
  88022. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88023. });
  88024. };
  88025. /*** Helpers ***/
  88026. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  88027. if (!this._cylinder) {
  88028. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  88029. height: this._height,
  88030. diameter: this._radius * 2,
  88031. }, this._scene);
  88032. this._cylinder.isVisible = false;
  88033. }
  88034. };
  88035. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  88036. var impostorObject = impostor.object;
  88037. this._prepareCylinder();
  88038. this._cylinder.position = this._cylinderPosition;
  88039. return this._cylinder.intersectsMesh(impostorObject, true);
  88040. };
  88041. return PhysicsUpdraftEvent;
  88042. }());
  88043. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  88044. /***** Vortex *****/
  88045. var PhysicsVortexEvent = /** @class */ (function () {
  88046. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  88047. this._scene = _scene;
  88048. this._origin = _origin;
  88049. this._radius = _radius;
  88050. this._strength = _strength;
  88051. this._height = _height;
  88052. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  88053. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  88054. this._updraftMultiplier = 0.02;
  88055. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  88056. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  88057. this._physicsEngine = this._scene.getPhysicsEngine();
  88058. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  88059. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  88060. this._tickCallback = this._tick.bind(this);
  88061. }
  88062. /**
  88063. * Returns the data related to the vortex event (cylinder).
  88064. * @returns {PhysicsVortexEventData}
  88065. */
  88066. PhysicsVortexEvent.prototype.getData = function () {
  88067. this._dataFetched = true;
  88068. return {
  88069. cylinder: this._cylinder,
  88070. };
  88071. };
  88072. /**
  88073. * Enables the vortex.
  88074. */
  88075. PhysicsVortexEvent.prototype.enable = function () {
  88076. this._tickCallback.call(this);
  88077. this._scene.registerBeforeRender(this._tickCallback);
  88078. };
  88079. /**
  88080. * Disables the cortex.
  88081. */
  88082. PhysicsVortexEvent.prototype.disable = function () {
  88083. this._scene.unregisterBeforeRender(this._tickCallback);
  88084. };
  88085. /**
  88086. * Disposes the sphere.
  88087. * @param {bolean} force
  88088. */
  88089. PhysicsVortexEvent.prototype.dispose = function (force) {
  88090. var _this = this;
  88091. if (force === void 0) { force = true; }
  88092. if (force) {
  88093. this._cylinder.dispose();
  88094. }
  88095. else {
  88096. setTimeout(function () {
  88097. if (!_this._dataFetched) {
  88098. _this._cylinder.dispose();
  88099. }
  88100. }, 0);
  88101. }
  88102. };
  88103. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  88104. if (impostor.mass === 0) {
  88105. return null;
  88106. }
  88107. if (!this._intersectsWithCylinder(impostor)) {
  88108. return null;
  88109. }
  88110. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  88111. return null;
  88112. }
  88113. var impostorObjectCenter = impostor.getObjectCenter();
  88114. 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)
  88115. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  88116. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  88117. var hit = ray.intersectsMesh(impostor.object);
  88118. var contactPoint = hit.pickedPoint;
  88119. if (!contactPoint) {
  88120. return null;
  88121. }
  88122. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  88123. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  88124. var directionToOrigin = contactPoint.normalize();
  88125. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88126. directionToOrigin = directionToOrigin.negate();
  88127. }
  88128. // TODO: find a more physically based solution
  88129. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  88130. var forceX = directionToOrigin.x * this._strength / 8;
  88131. var forceY = directionToOrigin.y * this._updraftMultiplier;
  88132. var forceZ = directionToOrigin.z * this._strength / 8;
  88133. }
  88134. else {
  88135. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  88136. var forceY = this._originTop.y * this._updraftMultiplier;
  88137. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  88138. }
  88139. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  88140. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  88141. return { force: force, contactPoint: impostorObjectCenter };
  88142. };
  88143. PhysicsVortexEvent.prototype._tick = function () {
  88144. var _this = this;
  88145. this._physicsEngine.getImpostors().forEach(function (impostor) {
  88146. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  88147. if (!impostorForceAndContactPoint) {
  88148. return;
  88149. }
  88150. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88151. });
  88152. };
  88153. /*** Helpers ***/
  88154. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  88155. if (!this._cylinder) {
  88156. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  88157. height: this._height,
  88158. diameter: this._radius * 2,
  88159. }, this._scene);
  88160. this._cylinder.isVisible = false;
  88161. }
  88162. };
  88163. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  88164. var impostorObject = impostor.object;
  88165. this._prepareCylinder();
  88166. this._cylinder.position = this._cylinderPosition;
  88167. return this._cylinder.intersectsMesh(impostorObject, true);
  88168. };
  88169. return PhysicsVortexEvent;
  88170. }());
  88171. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  88172. /***** Enums *****/
  88173. /**
  88174. * The strenght of the force in correspondence to the distance of the affected object
  88175. */
  88176. var PhysicsRadialImpulseFalloff;
  88177. (function (PhysicsRadialImpulseFalloff) {
  88178. /** Defines that impulse is constant in strength across it's whole radius */
  88179. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  88180. /** DEfines that impulse gets weaker if it's further from the origin */
  88181. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  88182. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  88183. /**
  88184. * The strenght of the force in correspondence to the distance of the affected object
  88185. */
  88186. var PhysicsUpdraftMode;
  88187. (function (PhysicsUpdraftMode) {
  88188. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  88189. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  88190. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  88191. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  88192. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  88193. })(BABYLON || (BABYLON = {}));
  88194. //# sourceMappingURL=babylon.physicsHelper.js.map
  88195. var BABYLON;
  88196. (function (BABYLON) {
  88197. var CannonJSPlugin = /** @class */ (function () {
  88198. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  88199. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  88200. if (iterations === void 0) { iterations = 10; }
  88201. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  88202. this.name = "CannonJSPlugin";
  88203. this._physicsMaterials = new Array();
  88204. this._fixedTimeStep = 1 / 60;
  88205. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  88206. this.BJSCANNON = CANNON;
  88207. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  88208. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  88209. this._tmpPosition = BABYLON.Vector3.Zero();
  88210. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  88211. this._tmpUnityRotation = new BABYLON.Quaternion();
  88212. if (!this.isSupported()) {
  88213. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  88214. return;
  88215. }
  88216. this._extendNamespace();
  88217. this.world = new this.BJSCANNON.World();
  88218. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  88219. this.world.solver.iterations = iterations;
  88220. }
  88221. CannonJSPlugin.prototype.setGravity = function (gravity) {
  88222. this.world.gravity.copy(gravity);
  88223. };
  88224. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  88225. this._fixedTimeStep = timeStep;
  88226. };
  88227. CannonJSPlugin.prototype.getTimeStep = function () {
  88228. return this._fixedTimeStep;
  88229. };
  88230. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  88231. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  88232. };
  88233. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88234. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88235. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88236. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  88237. };
  88238. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88239. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  88240. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  88241. impostor.physicsBody.applyForce(impulse, worldPoint);
  88242. };
  88243. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88244. //parent-child relationship. Does this impostor has a parent impostor?
  88245. if (impostor.parent) {
  88246. if (impostor.physicsBody) {
  88247. this.removePhysicsBody(impostor);
  88248. //TODO is that needed?
  88249. impostor.forceUpdate();
  88250. }
  88251. return;
  88252. }
  88253. //should a new body be created for this impostor?
  88254. if (impostor.isBodyInitRequired()) {
  88255. var shape = this._createShape(impostor);
  88256. //unregister events, if body is being changed
  88257. var oldBody = impostor.physicsBody;
  88258. if (oldBody) {
  88259. this.removePhysicsBody(impostor);
  88260. }
  88261. //create the body and material
  88262. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  88263. var bodyCreationObject = {
  88264. mass: impostor.getParam("mass"),
  88265. material: material
  88266. };
  88267. // A simple extend, in case native options were used.
  88268. var nativeOptions = impostor.getParam("nativeOptions");
  88269. for (var key in nativeOptions) {
  88270. if (nativeOptions.hasOwnProperty(key)) {
  88271. bodyCreationObject[key] = nativeOptions[key];
  88272. }
  88273. }
  88274. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  88275. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  88276. this.world.addEventListener("preStep", impostor.beforeStep);
  88277. this.world.addEventListener("postStep", impostor.afterStep);
  88278. impostor.physicsBody.addShape(shape);
  88279. this.world.add(impostor.physicsBody);
  88280. //try to keep the body moving in the right direction by taking old properties.
  88281. //Should be tested!
  88282. if (oldBody) {
  88283. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  88284. impostor.physicsBody[param].copy(oldBody[param]);
  88285. });
  88286. }
  88287. this._processChildMeshes(impostor);
  88288. }
  88289. //now update the body's transformation
  88290. this._updatePhysicsBodyTransformation(impostor);
  88291. };
  88292. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  88293. var _this = this;
  88294. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  88295. var currentRotation = mainImpostor.object.rotationQuaternion;
  88296. if (meshChildren.length) {
  88297. var processMesh = function (localPosition, mesh) {
  88298. if (!currentRotation || !mesh.rotationQuaternion) {
  88299. return;
  88300. }
  88301. var childImpostor = mesh.getPhysicsImpostor();
  88302. if (childImpostor) {
  88303. var parent = childImpostor.parent;
  88304. if (parent !== mainImpostor) {
  88305. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  88306. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  88307. if (childImpostor.physicsBody) {
  88308. _this.removePhysicsBody(childImpostor);
  88309. childImpostor.physicsBody = null;
  88310. }
  88311. childImpostor.parent = mainImpostor;
  88312. childImpostor.resetUpdateFlags();
  88313. 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));
  88314. //Add the mass of the children.
  88315. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  88316. }
  88317. }
  88318. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  88319. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  88320. };
  88321. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  88322. }
  88323. };
  88324. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88325. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  88326. this.world.removeEventListener("preStep", impostor.beforeStep);
  88327. this.world.removeEventListener("postStep", impostor.afterStep);
  88328. this.world.remove(impostor.physicsBody);
  88329. };
  88330. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88331. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88332. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88333. if (!mainBody || !connectedBody) {
  88334. return;
  88335. }
  88336. var constraint;
  88337. var jointData = impostorJoint.joint.jointData;
  88338. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  88339. var constraintData = {
  88340. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  88341. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  88342. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  88343. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  88344. maxForce: jointData.nativeParams.maxForce,
  88345. collideConnected: !!jointData.collision
  88346. };
  88347. switch (impostorJoint.joint.type) {
  88348. case BABYLON.PhysicsJoint.HingeJoint:
  88349. case BABYLON.PhysicsJoint.Hinge2Joint:
  88350. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  88351. break;
  88352. case BABYLON.PhysicsJoint.DistanceJoint:
  88353. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  88354. break;
  88355. case BABYLON.PhysicsJoint.SpringJoint:
  88356. var springData = jointData;
  88357. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  88358. restLength: springData.length,
  88359. stiffness: springData.stiffness,
  88360. damping: springData.damping,
  88361. localAnchorA: constraintData.pivotA,
  88362. localAnchorB: constraintData.pivotB
  88363. });
  88364. break;
  88365. case BABYLON.PhysicsJoint.LockJoint:
  88366. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  88367. break;
  88368. case BABYLON.PhysicsJoint.PointToPointJoint:
  88369. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88370. default:
  88371. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  88372. break;
  88373. }
  88374. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  88375. constraint.collideConnected = !!jointData.collision;
  88376. impostorJoint.joint.physicsJoint = constraint;
  88377. //don't add spring as constraint, as it is not one.
  88378. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  88379. this.world.addConstraint(constraint);
  88380. }
  88381. else {
  88382. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  88383. constraint.applyForce();
  88384. });
  88385. }
  88386. };
  88387. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88388. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  88389. };
  88390. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  88391. var index;
  88392. var mat;
  88393. for (index = 0; index < this._physicsMaterials.length; index++) {
  88394. mat = this._physicsMaterials[index];
  88395. if (mat.friction === friction && mat.restitution === restitution) {
  88396. return mat;
  88397. }
  88398. }
  88399. var currentMat = new this.BJSCANNON.Material(name);
  88400. currentMat.friction = friction;
  88401. currentMat.restitution = restitution;
  88402. this._physicsMaterials.push(currentMat);
  88403. return currentMat;
  88404. };
  88405. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  88406. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  88407. };
  88408. CannonJSPlugin.prototype._createShape = function (impostor) {
  88409. var object = impostor.object;
  88410. var returnValue;
  88411. var extendSize = impostor.getObjectExtendSize();
  88412. switch (impostor.type) {
  88413. case BABYLON.PhysicsImpostor.SphereImpostor:
  88414. var radiusX = extendSize.x;
  88415. var radiusY = extendSize.y;
  88416. var radiusZ = extendSize.z;
  88417. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  88418. break;
  88419. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  88420. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88421. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  88422. break;
  88423. case BABYLON.PhysicsImpostor.BoxImpostor:
  88424. var box = extendSize.scale(0.5);
  88425. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  88426. break;
  88427. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88428. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  88429. returnValue = new this.BJSCANNON.Plane();
  88430. break;
  88431. case BABYLON.PhysicsImpostor.MeshImpostor:
  88432. // should transform the vertex data to world coordinates!!
  88433. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  88434. var rawFaces = object.getIndices ? object.getIndices() : [];
  88435. if (!rawVerts)
  88436. return;
  88437. // get only scale! so the object could transform correctly.
  88438. var oldPosition = object.position.clone();
  88439. var oldRotation = object.rotation && object.rotation.clone();
  88440. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  88441. object.position.copyFromFloats(0, 0, 0);
  88442. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88443. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88444. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88445. var transform = object.computeWorldMatrix(true);
  88446. // convert rawVerts to object space
  88447. var temp = new Array();
  88448. var index;
  88449. for (index = 0; index < rawVerts.length; index += 3) {
  88450. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  88451. }
  88452. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  88453. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  88454. //now set back the transformation!
  88455. object.position.copyFrom(oldPosition);
  88456. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  88457. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  88458. break;
  88459. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  88460. var oldPosition2 = object.position.clone();
  88461. var oldRotation2 = object.rotation && object.rotation.clone();
  88462. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  88463. object.position.copyFromFloats(0, 0, 0);
  88464. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  88465. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  88466. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  88467. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  88468. returnValue = this._createHeightmap(object);
  88469. object.position.copyFrom(oldPosition2);
  88470. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  88471. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  88472. object.computeWorldMatrix(true);
  88473. break;
  88474. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88475. returnValue = new this.BJSCANNON.Particle();
  88476. break;
  88477. }
  88478. return returnValue;
  88479. };
  88480. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  88481. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  88482. var transform = object.computeWorldMatrix(true);
  88483. // convert rawVerts to object space
  88484. var temp = new Array();
  88485. var index;
  88486. for (index = 0; index < pos.length; index += 3) {
  88487. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  88488. }
  88489. pos = temp;
  88490. var matrix = new Array();
  88491. //For now pointDepth will not be used and will be automatically calculated.
  88492. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  88493. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  88494. var boundingInfo = object.getBoundingInfo();
  88495. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  88496. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  88497. var elementSize = dim * 2 / arraySize;
  88498. for (var i = 0; i < pos.length; i = i + 3) {
  88499. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  88500. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  88501. var y = -pos[i + 2] + minY;
  88502. if (!matrix[x]) {
  88503. matrix[x] = [];
  88504. }
  88505. if (!matrix[x][z]) {
  88506. matrix[x][z] = y;
  88507. }
  88508. matrix[x][z] = Math.max(y, matrix[x][z]);
  88509. }
  88510. for (var x = 0; x <= arraySize; ++x) {
  88511. if (!matrix[x]) {
  88512. var loc = 1;
  88513. while (!matrix[(x + loc) % arraySize]) {
  88514. loc++;
  88515. }
  88516. matrix[x] = matrix[(x + loc) % arraySize].slice();
  88517. //console.log("missing x", x);
  88518. }
  88519. for (var z = 0; z <= arraySize; ++z) {
  88520. if (!matrix[x][z]) {
  88521. var loc = 1;
  88522. var newValue;
  88523. while (newValue === undefined) {
  88524. newValue = matrix[x][(z + loc++) % arraySize];
  88525. }
  88526. matrix[x][z] = newValue;
  88527. }
  88528. }
  88529. }
  88530. var shape = new this.BJSCANNON.Heightfield(matrix, {
  88531. elementSize: elementSize
  88532. });
  88533. //For future reference, needed for body transformation
  88534. shape.minY = minY;
  88535. return shape;
  88536. };
  88537. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  88538. var object = impostor.object;
  88539. //make sure it is updated...
  88540. object.computeWorldMatrix && object.computeWorldMatrix(true);
  88541. // The delta between the mesh position and the mesh bounding box center
  88542. var bInfo = object.getBoundingInfo();
  88543. if (!bInfo)
  88544. return;
  88545. var center = impostor.getObjectCenter();
  88546. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  88547. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  88548. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  88549. this._tmpPosition.copyFrom(center);
  88550. var quaternion = object.rotationQuaternion;
  88551. if (!quaternion) {
  88552. return;
  88553. }
  88554. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  88555. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  88556. //-90 DEG in X, precalculated
  88557. quaternion = quaternion.multiply(this._minus90X);
  88558. //Invert! (Precalculated, 90 deg in X)
  88559. //No need to clone. this will never change.
  88560. impostor.setDeltaRotation(this._plus90X);
  88561. }
  88562. //If it is a heightfield, if should be centered.
  88563. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  88564. var mesh = object;
  88565. var boundingInfo = mesh.getBoundingInfo();
  88566. //calculate the correct body position:
  88567. var rotationQuaternion = mesh.rotationQuaternion;
  88568. mesh.rotationQuaternion = this._tmpUnityRotation;
  88569. mesh.computeWorldMatrix(true);
  88570. //get original center with no rotation
  88571. var c = center.clone();
  88572. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  88573. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  88574. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  88575. mesh.setPreTransformMatrix(p);
  88576. mesh.computeWorldMatrix(true);
  88577. //calculate the translation
  88578. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  88579. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  88580. //add it inverted to the delta
  88581. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  88582. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  88583. //rotation is back
  88584. mesh.rotationQuaternion = rotationQuaternion;
  88585. mesh.setPreTransformMatrix(oldPivot);
  88586. mesh.computeWorldMatrix(true);
  88587. }
  88588. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  88589. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  88590. //this._tmpPosition.copyFrom(object.position);
  88591. }
  88592. impostor.setDeltaPosition(this._tmpDeltaPosition);
  88593. //Now update the impostor object
  88594. impostor.physicsBody.position.copy(this._tmpPosition);
  88595. impostor.physicsBody.quaternion.copy(quaternion);
  88596. };
  88597. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88598. impostor.object.position.copyFrom(impostor.physicsBody.position);
  88599. if (impostor.object.rotationQuaternion) {
  88600. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  88601. }
  88602. };
  88603. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88604. impostor.physicsBody.position.copy(newPosition);
  88605. impostor.physicsBody.quaternion.copy(newRotation);
  88606. };
  88607. CannonJSPlugin.prototype.isSupported = function () {
  88608. return this.BJSCANNON !== undefined;
  88609. };
  88610. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88611. impostor.physicsBody.velocity.copy(velocity);
  88612. };
  88613. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88614. impostor.physicsBody.angularVelocity.copy(velocity);
  88615. };
  88616. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88617. var v = impostor.physicsBody.velocity;
  88618. if (!v) {
  88619. return null;
  88620. }
  88621. return new BABYLON.Vector3(v.x, v.y, v.z);
  88622. };
  88623. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88624. var v = impostor.physicsBody.angularVelocity;
  88625. if (!v) {
  88626. return null;
  88627. }
  88628. return new BABYLON.Vector3(v.x, v.y, v.z);
  88629. };
  88630. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88631. impostor.physicsBody.mass = mass;
  88632. impostor.physicsBody.updateMassProperties();
  88633. };
  88634. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  88635. return impostor.physicsBody.mass;
  88636. };
  88637. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  88638. return impostor.physicsBody.material.friction;
  88639. };
  88640. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88641. impostor.physicsBody.material.friction = friction;
  88642. };
  88643. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88644. return impostor.physicsBody.material.restitution;
  88645. };
  88646. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88647. impostor.physicsBody.material.restitution = restitution;
  88648. };
  88649. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  88650. impostor.physicsBody.sleep();
  88651. };
  88652. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  88653. impostor.physicsBody.wakeUp();
  88654. };
  88655. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88656. joint.physicsJoint.distance = maxDistance;
  88657. };
  88658. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88659. // if (!motorIndex) {
  88660. // joint.physicsJoint.enableMotor();
  88661. // }
  88662. // }
  88663. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88664. // if (!motorIndex) {
  88665. // joint.physicsJoint.disableMotor();
  88666. // }
  88667. // }
  88668. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88669. if (!motorIndex) {
  88670. joint.physicsJoint.enableMotor();
  88671. joint.physicsJoint.setMotorSpeed(speed);
  88672. if (maxForce) {
  88673. this.setLimit(joint, maxForce);
  88674. }
  88675. }
  88676. };
  88677. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  88678. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  88679. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  88680. };
  88681. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88682. var body = impostor.physicsBody;
  88683. mesh.position.x = body.position.x;
  88684. mesh.position.y = body.position.y;
  88685. mesh.position.z = body.position.z;
  88686. if (mesh.rotationQuaternion) {
  88687. mesh.rotationQuaternion.x = body.quaternion.x;
  88688. mesh.rotationQuaternion.y = body.quaternion.y;
  88689. mesh.rotationQuaternion.z = body.quaternion.z;
  88690. mesh.rotationQuaternion.w = body.quaternion.w;
  88691. }
  88692. };
  88693. CannonJSPlugin.prototype.getRadius = function (impostor) {
  88694. var shape = impostor.physicsBody.shapes[0];
  88695. return shape.boundingSphereRadius;
  88696. };
  88697. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88698. var shape = impostor.physicsBody.shapes[0];
  88699. result.x = shape.halfExtents.x * 2;
  88700. result.y = shape.halfExtents.y * 2;
  88701. result.z = shape.halfExtents.z * 2;
  88702. };
  88703. CannonJSPlugin.prototype.dispose = function () {
  88704. };
  88705. CannonJSPlugin.prototype._extendNamespace = function () {
  88706. //this will force cannon to execute at least one step when using interpolation
  88707. var step_tmp1 = new this.BJSCANNON.Vec3();
  88708. var Engine = this.BJSCANNON;
  88709. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  88710. maxSubSteps = maxSubSteps || 10;
  88711. timeSinceLastCalled = timeSinceLastCalled || 0;
  88712. if (timeSinceLastCalled === 0) {
  88713. this.internalStep(dt);
  88714. this.time += dt;
  88715. }
  88716. else {
  88717. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  88718. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  88719. var t0 = performance.now();
  88720. for (var i = 0; i !== internalSteps; i++) {
  88721. this.internalStep(dt);
  88722. if (performance.now() - t0 > dt * 1000) {
  88723. break;
  88724. }
  88725. }
  88726. this.time += timeSinceLastCalled;
  88727. var h = this.time % dt;
  88728. var h_div_dt = h / dt;
  88729. var interpvelo = step_tmp1;
  88730. var bodies = this.bodies;
  88731. for (var j = 0; j !== bodies.length; j++) {
  88732. var b = bodies[j];
  88733. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  88734. b.position.vsub(b.previousPosition, interpvelo);
  88735. interpvelo.scale(h_div_dt, interpvelo);
  88736. b.position.vadd(interpvelo, b.interpolatedPosition);
  88737. }
  88738. else {
  88739. b.interpolatedPosition.copy(b.position);
  88740. b.interpolatedQuaternion.copy(b.quaternion);
  88741. }
  88742. }
  88743. }
  88744. };
  88745. };
  88746. return CannonJSPlugin;
  88747. }());
  88748. BABYLON.CannonJSPlugin = CannonJSPlugin;
  88749. })(BABYLON || (BABYLON = {}));
  88750. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  88751. var BABYLON;
  88752. (function (BABYLON) {
  88753. var OimoJSPlugin = /** @class */ (function () {
  88754. function OimoJSPlugin(iterations) {
  88755. this.name = "OimoJSPlugin";
  88756. this._tmpImpostorsArray = [];
  88757. this._tmpPositionVector = BABYLON.Vector3.Zero();
  88758. this.BJSOIMO = OIMO;
  88759. this.world = new this.BJSOIMO.World({
  88760. iterations: iterations
  88761. });
  88762. this.world.clear();
  88763. }
  88764. OimoJSPlugin.prototype.setGravity = function (gravity) {
  88765. this.world.gravity.copy(gravity);
  88766. };
  88767. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  88768. this.world.timeStep = timeStep;
  88769. };
  88770. OimoJSPlugin.prototype.getTimeStep = function () {
  88771. return this.world.timeStep;
  88772. };
  88773. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  88774. var _this = this;
  88775. impostors.forEach(function (impostor) {
  88776. impostor.beforeStep();
  88777. });
  88778. this.world.step();
  88779. impostors.forEach(function (impostor) {
  88780. impostor.afterStep();
  88781. //update the ordered impostors array
  88782. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  88783. });
  88784. //check for collisions
  88785. var contact = this.world.contacts;
  88786. while (contact !== null) {
  88787. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  88788. contact = contact.next;
  88789. continue;
  88790. }
  88791. //is this body colliding with any other? get the impostor
  88792. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  88793. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  88794. if (!mainImpostor || !collidingImpostor) {
  88795. contact = contact.next;
  88796. continue;
  88797. }
  88798. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  88799. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  88800. contact = contact.next;
  88801. }
  88802. };
  88803. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88804. var mass = impostor.physicsBody.mass;
  88805. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  88806. };
  88807. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88808. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  88809. this.applyImpulse(impostor, force, contactPoint);
  88810. };
  88811. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88812. var _this = this;
  88813. //parent-child relationship. Does this impostor has a parent impostor?
  88814. if (impostor.parent) {
  88815. if (impostor.physicsBody) {
  88816. this.removePhysicsBody(impostor);
  88817. //TODO is that needed?
  88818. impostor.forceUpdate();
  88819. }
  88820. return;
  88821. }
  88822. if (impostor.isBodyInitRequired()) {
  88823. var bodyConfig = {
  88824. name: impostor.uniqueId,
  88825. //Oimo must have mass, also for static objects.
  88826. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  88827. size: [],
  88828. type: [],
  88829. pos: [],
  88830. posShape: [],
  88831. rot: [],
  88832. rotShape: [],
  88833. move: impostor.getParam("mass") !== 0,
  88834. density: impostor.getParam("mass"),
  88835. friction: impostor.getParam("friction"),
  88836. restitution: impostor.getParam("restitution"),
  88837. //Supporting older versions of Oimo
  88838. world: this.world
  88839. };
  88840. var impostors = [impostor];
  88841. var addToArray = function (parent) {
  88842. if (!parent.getChildMeshes)
  88843. return;
  88844. parent.getChildMeshes().forEach(function (m) {
  88845. if (m.physicsImpostor) {
  88846. impostors.push(m.physicsImpostor);
  88847. //m.physicsImpostor._init();
  88848. }
  88849. });
  88850. };
  88851. addToArray(impostor.object);
  88852. var checkWithEpsilon_1 = function (value) {
  88853. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  88854. };
  88855. var globalQuaternion_1 = new BABYLON.Quaternion();
  88856. impostors.forEach(function (i) {
  88857. if (!i.object.rotationQuaternion) {
  88858. return;
  88859. }
  88860. //get the correct bounding box
  88861. var oldQuaternion = i.object.rotationQuaternion;
  88862. globalQuaternion_1 = oldQuaternion.clone();
  88863. var rot = oldQuaternion.toEulerAngles();
  88864. var extendSize = i.getObjectExtendSize();
  88865. var radToDeg = 57.295779513082320876;
  88866. if (i === impostor) {
  88867. var center = impostor.getObjectCenter();
  88868. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  88869. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  88870. //Can also use Array.prototype.push.apply
  88871. bodyConfig.pos.push(center.x);
  88872. bodyConfig.pos.push(center.y);
  88873. bodyConfig.pos.push(center.z);
  88874. bodyConfig.posShape.push(0, 0, 0);
  88875. //tmp solution
  88876. bodyConfig.rot.push(0);
  88877. bodyConfig.rot.push(0);
  88878. bodyConfig.rot.push(0);
  88879. bodyConfig.rotShape.push(0, 0, 0);
  88880. }
  88881. else {
  88882. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  88883. bodyConfig.posShape.push(localPosition.x);
  88884. bodyConfig.posShape.push(localPosition.y);
  88885. bodyConfig.posShape.push(localPosition.z);
  88886. bodyConfig.pos.push(0, 0, 0);
  88887. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  88888. bodyConfig.rot.push(0);
  88889. bodyConfig.rot.push(0);
  88890. bodyConfig.rot.push(0);
  88891. bodyConfig.rotShape.push(rot.x * radToDeg);
  88892. bodyConfig.rotShape.push(rot.y * radToDeg);
  88893. bodyConfig.rotShape.push(rot.z * radToDeg);
  88894. }
  88895. // register mesh
  88896. switch (i.type) {
  88897. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88898. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  88899. case BABYLON.PhysicsImpostor.SphereImpostor:
  88900. var radiusX = extendSize.x;
  88901. var radiusY = extendSize.y;
  88902. var radiusZ = extendSize.z;
  88903. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  88904. bodyConfig.type.push('sphere');
  88905. //due to the way oimo works with compounds, add 3 times
  88906. bodyConfig.size.push(size);
  88907. bodyConfig.size.push(size);
  88908. bodyConfig.size.push(size);
  88909. break;
  88910. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88911. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  88912. var sizeY = checkWithEpsilon_1(extendSize.y);
  88913. bodyConfig.type.push('cylinder');
  88914. bodyConfig.size.push(sizeX);
  88915. bodyConfig.size.push(sizeY);
  88916. //due to the way oimo works with compounds, add one more value.
  88917. bodyConfig.size.push(sizeY);
  88918. break;
  88919. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88920. case BABYLON.PhysicsImpostor.BoxImpostor:
  88921. default:
  88922. var sizeX = checkWithEpsilon_1(extendSize.x);
  88923. var sizeY = checkWithEpsilon_1(extendSize.y);
  88924. var sizeZ = checkWithEpsilon_1(extendSize.z);
  88925. bodyConfig.type.push('box');
  88926. //if (i === impostor) {
  88927. bodyConfig.size.push(sizeX);
  88928. bodyConfig.size.push(sizeY);
  88929. bodyConfig.size.push(sizeZ);
  88930. //} else {
  88931. // bodyConfig.size.push(0,0,0);
  88932. //}
  88933. break;
  88934. }
  88935. //actually not needed, but hey...
  88936. i.object.rotationQuaternion = oldQuaternion;
  88937. });
  88938. impostor.physicsBody = this.world.add(bodyConfig);
  88939. // set the quaternion, ignoring the previously defined (euler) rotation
  88940. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  88941. // update with delta 0, so the body will reveive the new rotation.
  88942. impostor.physicsBody.updatePosition(0);
  88943. }
  88944. else {
  88945. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  88946. }
  88947. impostor.setDeltaPosition(this._tmpPositionVector);
  88948. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  88949. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  88950. };
  88951. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88952. //impostor.physicsBody.dispose();
  88953. //Same as : (older oimo versions)
  88954. this.world.removeRigidBody(impostor.physicsBody);
  88955. };
  88956. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88957. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88958. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88959. if (!mainBody || !connectedBody) {
  88960. return;
  88961. }
  88962. var jointData = impostorJoint.joint.jointData;
  88963. var options = jointData.nativeParams || {};
  88964. var type;
  88965. var nativeJointData = {
  88966. body1: mainBody,
  88967. body2: connectedBody,
  88968. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  88969. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  88970. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  88971. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  88972. min: options.min,
  88973. max: options.max,
  88974. collision: options.collision || jointData.collision,
  88975. spring: options.spring,
  88976. //supporting older version of Oimo
  88977. world: this.world
  88978. };
  88979. switch (impostorJoint.joint.type) {
  88980. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88981. type = "jointBall";
  88982. break;
  88983. case BABYLON.PhysicsJoint.SpringJoint:
  88984. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  88985. var springData = jointData;
  88986. nativeJointData.min = springData.length || nativeJointData.min;
  88987. //Max should also be set, just make sure it is at least min
  88988. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  88989. case BABYLON.PhysicsJoint.DistanceJoint:
  88990. type = "jointDistance";
  88991. nativeJointData.max = jointData.maxDistance;
  88992. break;
  88993. case BABYLON.PhysicsJoint.PrismaticJoint:
  88994. type = "jointPrisme";
  88995. break;
  88996. case BABYLON.PhysicsJoint.SliderJoint:
  88997. type = "jointSlide";
  88998. break;
  88999. case BABYLON.PhysicsJoint.WheelJoint:
  89000. type = "jointWheel";
  89001. break;
  89002. case BABYLON.PhysicsJoint.HingeJoint:
  89003. default:
  89004. type = "jointHinge";
  89005. break;
  89006. }
  89007. nativeJointData.type = type;
  89008. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  89009. };
  89010. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89011. //Bug in Oimo prevents us from disposing a joint in the playground
  89012. //joint.joint.physicsJoint.dispose();
  89013. //So we will bruteforce it!
  89014. try {
  89015. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  89016. }
  89017. catch (e) {
  89018. BABYLON.Tools.Warn(e);
  89019. }
  89020. };
  89021. OimoJSPlugin.prototype.isSupported = function () {
  89022. return this.BJSOIMO !== undefined;
  89023. };
  89024. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89025. if (!impostor.physicsBody.sleeping) {
  89026. //TODO check that
  89027. /*if (impostor.physicsBody.shapes.next) {
  89028. var parentShape = this._getLastShape(impostor.physicsBody);
  89029. impostor.object.position.copyFrom(parentShape.position);
  89030. console.log(parentShape.position);
  89031. } else {*/
  89032. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  89033. //}
  89034. if (impostor.object.rotationQuaternion) {
  89035. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  89036. }
  89037. }
  89038. };
  89039. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89040. var body = impostor.physicsBody;
  89041. body.position.copy(newPosition);
  89042. body.orientation.copy(newRotation);
  89043. body.syncShapes();
  89044. body.awake();
  89045. };
  89046. /*private _getLastShape(body: any): any {
  89047. var lastShape = body.shapes;
  89048. while (lastShape.next) {
  89049. lastShape = lastShape.next;
  89050. }
  89051. return lastShape;
  89052. }*/
  89053. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89054. impostor.physicsBody.linearVelocity.copy(velocity);
  89055. };
  89056. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89057. impostor.physicsBody.angularVelocity.copy(velocity);
  89058. };
  89059. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89060. var v = impostor.physicsBody.linearVelocity;
  89061. if (!v) {
  89062. return null;
  89063. }
  89064. return new BABYLON.Vector3(v.x, v.y, v.z);
  89065. };
  89066. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89067. var v = impostor.physicsBody.angularVelocity;
  89068. if (!v) {
  89069. return null;
  89070. }
  89071. return new BABYLON.Vector3(v.x, v.y, v.z);
  89072. };
  89073. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89074. var staticBody = mass === 0;
  89075. //this will actually set the body's density and not its mass.
  89076. //But this is how oimo treats the mass variable.
  89077. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  89078. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  89079. };
  89080. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  89081. return impostor.physicsBody.shapes.density;
  89082. };
  89083. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  89084. return impostor.physicsBody.shapes.friction;
  89085. };
  89086. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89087. impostor.physicsBody.shapes.friction = friction;
  89088. };
  89089. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89090. return impostor.physicsBody.shapes.restitution;
  89091. };
  89092. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89093. impostor.physicsBody.shapes.restitution = restitution;
  89094. };
  89095. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  89096. impostor.physicsBody.sleep();
  89097. };
  89098. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  89099. impostor.physicsBody.awake();
  89100. };
  89101. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89102. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  89103. if (minDistance !== void 0) {
  89104. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  89105. }
  89106. };
  89107. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89108. //TODO separate rotational and transational motors.
  89109. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89110. if (motor) {
  89111. motor.setMotor(speed, maxForce);
  89112. }
  89113. };
  89114. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  89115. //TODO separate rotational and transational motors.
  89116. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  89117. if (motor) {
  89118. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  89119. }
  89120. };
  89121. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89122. var body = impostor.physicsBody;
  89123. mesh.position.x = body.position.x;
  89124. mesh.position.y = body.position.y;
  89125. mesh.position.z = body.position.z;
  89126. if (mesh.rotationQuaternion) {
  89127. mesh.rotationQuaternion.x = body.orientation.x;
  89128. mesh.rotationQuaternion.y = body.orientation.y;
  89129. mesh.rotationQuaternion.z = body.orientation.z;
  89130. mesh.rotationQuaternion.w = body.orientation.s;
  89131. }
  89132. };
  89133. OimoJSPlugin.prototype.getRadius = function (impostor) {
  89134. return impostor.physicsBody.shapes.radius;
  89135. };
  89136. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89137. var shape = impostor.physicsBody.shapes;
  89138. result.x = shape.halfWidth * 2;
  89139. result.y = shape.halfHeight * 2;
  89140. result.z = shape.halfDepth * 2;
  89141. };
  89142. OimoJSPlugin.prototype.dispose = function () {
  89143. this.world.clear();
  89144. };
  89145. return OimoJSPlugin;
  89146. }());
  89147. BABYLON.OimoJSPlugin = OimoJSPlugin;
  89148. })(BABYLON || (BABYLON = {}));
  89149. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  89150. var BABYLON;
  89151. (function (BABYLON) {
  89152. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  89153. // All values and structures referenced from:
  89154. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  89155. var DDS_MAGIC = 0x20534444;
  89156. var
  89157. //DDSD_CAPS = 0x1,
  89158. //DDSD_HEIGHT = 0x2,
  89159. //DDSD_WIDTH = 0x4,
  89160. //DDSD_PITCH = 0x8,
  89161. //DDSD_PIXELFORMAT = 0x1000,
  89162. DDSD_MIPMAPCOUNT = 0x20000;
  89163. //DDSD_LINEARSIZE = 0x80000,
  89164. //DDSD_DEPTH = 0x800000;
  89165. // var DDSCAPS_COMPLEX = 0x8,
  89166. // DDSCAPS_MIPMAP = 0x400000,
  89167. // DDSCAPS_TEXTURE = 0x1000;
  89168. var DDSCAPS2_CUBEMAP = 0x200;
  89169. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  89170. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  89171. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  89172. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  89173. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  89174. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  89175. // DDSCAPS2_VOLUME = 0x200000;
  89176. var
  89177. //DDPF_ALPHAPIXELS = 0x1,
  89178. //DDPF_ALPHA = 0x2,
  89179. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  89180. //DDPF_YUV = 0x200,
  89181. DDPF_LUMINANCE = 0x20000;
  89182. function FourCCToInt32(value) {
  89183. return value.charCodeAt(0) +
  89184. (value.charCodeAt(1) << 8) +
  89185. (value.charCodeAt(2) << 16) +
  89186. (value.charCodeAt(3) << 24);
  89187. }
  89188. function Int32ToFourCC(value) {
  89189. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  89190. }
  89191. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  89192. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  89193. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  89194. var FOURCC_DX10 = FourCCToInt32("DX10");
  89195. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  89196. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  89197. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  89198. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  89199. var headerLengthInt = 31; // The header length in 32 bit ints
  89200. // Offsets into the header array
  89201. var off_magic = 0;
  89202. var off_size = 1;
  89203. var off_flags = 2;
  89204. var off_height = 3;
  89205. var off_width = 4;
  89206. var off_mipmapCount = 7;
  89207. var off_pfFlags = 20;
  89208. var off_pfFourCC = 21;
  89209. var off_RGBbpp = 22;
  89210. var off_RMask = 23;
  89211. var off_GMask = 24;
  89212. var off_BMask = 25;
  89213. var off_AMask = 26;
  89214. // var off_caps1 = 27;
  89215. var off_caps2 = 28;
  89216. // var off_caps3 = 29;
  89217. // var off_caps4 = 30;
  89218. var off_dxgiFormat = 32;
  89219. ;
  89220. var DDSTools = /** @class */ (function () {
  89221. function DDSTools() {
  89222. }
  89223. DDSTools.GetDDSInfo = function (arrayBuffer) {
  89224. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89225. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  89226. var mipmapCount = 1;
  89227. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  89228. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89229. }
  89230. var fourCC = header[off_pfFourCC];
  89231. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  89232. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89233. switch (fourCC) {
  89234. case FOURCC_D3DFMT_R16G16B16A16F:
  89235. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89236. break;
  89237. case FOURCC_D3DFMT_R32G32B32A32F:
  89238. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89239. break;
  89240. case FOURCC_DX10:
  89241. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  89242. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89243. break;
  89244. }
  89245. }
  89246. return {
  89247. width: header[off_width],
  89248. height: header[off_height],
  89249. mipmapCount: mipmapCount,
  89250. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  89251. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  89252. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  89253. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  89254. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  89255. dxgiFormat: dxgiFormat,
  89256. textureType: textureType
  89257. };
  89258. };
  89259. DDSTools._ToHalfFloat = function (value) {
  89260. if (!DDSTools._FloatView) {
  89261. DDSTools._FloatView = new Float32Array(1);
  89262. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  89263. }
  89264. DDSTools._FloatView[0] = value;
  89265. var x = DDSTools._Int32View[0];
  89266. var bits = (x >> 16) & 0x8000; /* Get the sign */
  89267. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  89268. var e = (x >> 23) & 0xff; /* Using int is faster here */
  89269. /* If zero, or denormal, or exponent underflows too much for a denormal
  89270. * half, return signed zero. */
  89271. if (e < 103) {
  89272. return bits;
  89273. }
  89274. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  89275. if (e > 142) {
  89276. bits |= 0x7c00;
  89277. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  89278. * not Inf, so make sure we set one mantissa bit too. */
  89279. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  89280. return bits;
  89281. }
  89282. /* If exponent underflows but not too much, return a denormal */
  89283. if (e < 113) {
  89284. m |= 0x0800;
  89285. /* Extra rounding may overflow and set mantissa to 0 and exponent
  89286. * to 1, which is OK. */
  89287. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  89288. return bits;
  89289. }
  89290. bits |= ((e - 112) << 10) | (m >> 1);
  89291. bits += m & 1;
  89292. return bits;
  89293. };
  89294. DDSTools._FromHalfFloat = function (value) {
  89295. var s = (value & 0x8000) >> 15;
  89296. var e = (value & 0x7C00) >> 10;
  89297. var f = value & 0x03FF;
  89298. if (e === 0) {
  89299. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  89300. }
  89301. else if (e == 0x1F) {
  89302. return f ? NaN : ((s ? -1 : 1) * Infinity);
  89303. }
  89304. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  89305. };
  89306. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89307. var destArray = new Float32Array(dataLength);
  89308. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89309. var index = 0;
  89310. for (var y = 0; y < height; y++) {
  89311. for (var x = 0; x < width; x++) {
  89312. var srcPos = (x + y * width) * 4;
  89313. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  89314. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  89315. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  89316. if (DDSTools.StoreLODInAlphaChannel) {
  89317. destArray[index + 3] = lod;
  89318. }
  89319. else {
  89320. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  89321. }
  89322. index += 4;
  89323. }
  89324. }
  89325. return destArray;
  89326. };
  89327. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89328. if (DDSTools.StoreLODInAlphaChannel) {
  89329. var destArray = new Uint16Array(dataLength);
  89330. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89331. var index = 0;
  89332. for (var y = 0; y < height; y++) {
  89333. for (var x = 0; x < width; x++) {
  89334. var srcPos = (x + y * width) * 4;
  89335. destArray[index] = srcData[srcPos];
  89336. destArray[index + 1] = srcData[srcPos + 1];
  89337. destArray[index + 2] = srcData[srcPos + 2];
  89338. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  89339. index += 4;
  89340. }
  89341. }
  89342. return destArray;
  89343. }
  89344. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  89345. };
  89346. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89347. if (DDSTools.StoreLODInAlphaChannel) {
  89348. var destArray = new Float32Array(dataLength);
  89349. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89350. var index = 0;
  89351. for (var y = 0; y < height; y++) {
  89352. for (var x = 0; x < width; x++) {
  89353. var srcPos = (x + y * width) * 4;
  89354. destArray[index] = srcData[srcPos];
  89355. destArray[index + 1] = srcData[srcPos + 1];
  89356. destArray[index + 2] = srcData[srcPos + 2];
  89357. destArray[index + 3] = lod;
  89358. index += 4;
  89359. }
  89360. }
  89361. return destArray;
  89362. }
  89363. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  89364. };
  89365. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89366. var destArray = new Uint8Array(dataLength);
  89367. var srcData = new Float32Array(arrayBuffer, dataOffset);
  89368. var index = 0;
  89369. for (var y = 0; y < height; y++) {
  89370. for (var x = 0; x < width; x++) {
  89371. var srcPos = (x + y * width) * 4;
  89372. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  89373. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  89374. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  89375. if (DDSTools.StoreLODInAlphaChannel) {
  89376. destArray[index + 3] = lod;
  89377. }
  89378. else {
  89379. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  89380. }
  89381. index += 4;
  89382. }
  89383. }
  89384. return destArray;
  89385. };
  89386. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  89387. var destArray = new Uint8Array(dataLength);
  89388. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  89389. var index = 0;
  89390. for (var y = 0; y < height; y++) {
  89391. for (var x = 0; x < width; x++) {
  89392. var srcPos = (x + y * width) * 4;
  89393. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  89394. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  89395. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  89396. if (DDSTools.StoreLODInAlphaChannel) {
  89397. destArray[index + 3] = lod;
  89398. }
  89399. else {
  89400. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  89401. }
  89402. index += 4;
  89403. }
  89404. }
  89405. return destArray;
  89406. };
  89407. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  89408. var byteArray = new Uint8Array(dataLength);
  89409. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89410. var index = 0;
  89411. for (var y = 0; y < height; y++) {
  89412. for (var x = 0; x < width; x++) {
  89413. var srcPos = (x + y * width) * 4;
  89414. byteArray[index] = srcData[srcPos + rOffset];
  89415. byteArray[index + 1] = srcData[srcPos + gOffset];
  89416. byteArray[index + 2] = srcData[srcPos + bOffset];
  89417. byteArray[index + 3] = srcData[srcPos + aOffset];
  89418. index += 4;
  89419. }
  89420. }
  89421. return byteArray;
  89422. };
  89423. DDSTools._ExtractLongWordOrder = function (value) {
  89424. if (value === 0 || value === 255 || value === -16777216) {
  89425. return 0;
  89426. }
  89427. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  89428. };
  89429. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  89430. var byteArray = new Uint8Array(dataLength);
  89431. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89432. var index = 0;
  89433. for (var y = 0; y < height; y++) {
  89434. for (var x = 0; x < width; x++) {
  89435. var srcPos = (x + y * width) * 3;
  89436. byteArray[index] = srcData[srcPos + rOffset];
  89437. byteArray[index + 1] = srcData[srcPos + gOffset];
  89438. byteArray[index + 2] = srcData[srcPos + bOffset];
  89439. index += 3;
  89440. }
  89441. }
  89442. return byteArray;
  89443. };
  89444. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  89445. var byteArray = new Uint8Array(dataLength);
  89446. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  89447. var index = 0;
  89448. for (var y = 0; y < height; y++) {
  89449. for (var x = 0; x < width; x++) {
  89450. var srcPos = (x + y * width);
  89451. byteArray[index] = srcData[srcPos];
  89452. index++;
  89453. }
  89454. }
  89455. return byteArray;
  89456. };
  89457. /**
  89458. * Uploads DDS Levels to a Babylon Texture
  89459. * @hidden
  89460. */
  89461. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  89462. if (lodIndex === void 0) { lodIndex = -1; }
  89463. var sphericalPolynomialFaces = null;
  89464. if (info.sphericalPolynomial) {
  89465. sphericalPolynomialFaces = new Array();
  89466. }
  89467. var ext = engine.getCaps().s3tc;
  89468. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  89469. var fourCC, width, height, dataLength = 0, dataOffset;
  89470. var byteArray, mipmapCount, mip;
  89471. var internalCompressedFormat = 0;
  89472. var blockBytes = 1;
  89473. if (header[off_magic] !== DDS_MAGIC) {
  89474. BABYLON.Tools.Error("Invalid magic number in DDS header");
  89475. return;
  89476. }
  89477. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  89478. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  89479. return;
  89480. }
  89481. if (info.isCompressed && !ext) {
  89482. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  89483. return;
  89484. }
  89485. var bpp = header[off_RGBbpp];
  89486. dataOffset = header[off_size] + 4;
  89487. var computeFormats = false;
  89488. if (info.isFourCC) {
  89489. fourCC = header[off_pfFourCC];
  89490. switch (fourCC) {
  89491. case FOURCC_DXT1:
  89492. blockBytes = 8;
  89493. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  89494. break;
  89495. case FOURCC_DXT3:
  89496. blockBytes = 16;
  89497. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  89498. break;
  89499. case FOURCC_DXT5:
  89500. blockBytes = 16;
  89501. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  89502. break;
  89503. case FOURCC_D3DFMT_R16G16B16A16F:
  89504. computeFormats = true;
  89505. break;
  89506. case FOURCC_D3DFMT_R32G32B32A32F:
  89507. computeFormats = true;
  89508. break;
  89509. case FOURCC_DX10:
  89510. // There is an additionnal header so dataOffset need to be changed
  89511. dataOffset += 5 * 4; // 5 uints
  89512. var supported = false;
  89513. switch (info.dxgiFormat) {
  89514. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  89515. computeFormats = true;
  89516. supported = true;
  89517. break;
  89518. case DXGI_FORMAT_B8G8R8X8_UNORM:
  89519. info.isRGB = true;
  89520. info.isFourCC = false;
  89521. bpp = 32;
  89522. supported = true;
  89523. break;
  89524. }
  89525. if (supported) {
  89526. break;
  89527. }
  89528. default:
  89529. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  89530. return;
  89531. }
  89532. }
  89533. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  89534. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  89535. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  89536. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  89537. if (computeFormats) {
  89538. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  89539. }
  89540. mipmapCount = 1;
  89541. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  89542. mipmapCount = Math.max(1, header[off_mipmapCount]);
  89543. }
  89544. for (var face = 0; face < faces; face++) {
  89545. width = header[off_width];
  89546. height = header[off_height];
  89547. for (mip = 0; mip < mipmapCount; ++mip) {
  89548. if (lodIndex === -1 || lodIndex === mip) {
  89549. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  89550. var i = (lodIndex === -1) ? mip : 0;
  89551. if (!info.isCompressed && info.isFourCC) {
  89552. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89553. dataLength = width * height * 4;
  89554. var floatArray = null;
  89555. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  89556. if (bpp === 128) {
  89557. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89558. if (sphericalPolynomialFaces && i == 0) {
  89559. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89560. }
  89561. }
  89562. else if (bpp === 64) {
  89563. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89564. if (sphericalPolynomialFaces && i == 0) {
  89565. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89566. }
  89567. }
  89568. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89569. }
  89570. else {
  89571. if (bpp === 128) {
  89572. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89573. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89574. if (sphericalPolynomialFaces && i == 0) {
  89575. sphericalPolynomialFaces.push(floatArray);
  89576. }
  89577. }
  89578. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  89579. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89580. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89581. if (sphericalPolynomialFaces && i == 0) {
  89582. sphericalPolynomialFaces.push(floatArray);
  89583. }
  89584. }
  89585. else { // 64
  89586. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89587. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89588. if (sphericalPolynomialFaces && i == 0) {
  89589. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89590. }
  89591. }
  89592. }
  89593. if (floatArray) {
  89594. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  89595. }
  89596. }
  89597. else if (info.isRGB) {
  89598. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89599. if (bpp === 24) {
  89600. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  89601. dataLength = width * height * 3;
  89602. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  89603. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89604. }
  89605. else { // 32
  89606. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89607. dataLength = width * height * 4;
  89608. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  89609. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89610. }
  89611. }
  89612. else if (info.isLuminance) {
  89613. var unpackAlignment = engine._getUnpackAlignement();
  89614. var unpaddedRowSize = width;
  89615. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  89616. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  89617. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  89618. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  89619. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89620. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89621. }
  89622. else {
  89623. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  89624. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  89625. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89626. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  89627. }
  89628. }
  89629. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  89630. width *= 0.5;
  89631. height *= 0.5;
  89632. width = Math.max(1.0, width);
  89633. height = Math.max(1.0, height);
  89634. }
  89635. if (currentFace !== undefined) {
  89636. // Loading a single face
  89637. break;
  89638. }
  89639. }
  89640. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  89641. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  89642. size: header[off_width],
  89643. right: sphericalPolynomialFaces[0],
  89644. left: sphericalPolynomialFaces[1],
  89645. up: sphericalPolynomialFaces[2],
  89646. down: sphericalPolynomialFaces[3],
  89647. front: sphericalPolynomialFaces[4],
  89648. back: sphericalPolynomialFaces[5],
  89649. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  89650. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89651. gammaSpace: false,
  89652. });
  89653. }
  89654. else {
  89655. info.sphericalPolynomial = undefined;
  89656. }
  89657. };
  89658. DDSTools.StoreLODInAlphaChannel = false;
  89659. return DDSTools;
  89660. }());
  89661. BABYLON.DDSTools = DDSTools;
  89662. })(BABYLON || (BABYLON = {}));
  89663. //# sourceMappingURL=babylon.dds.js.map
  89664. var BABYLON;
  89665. (function (BABYLON) {
  89666. /**
  89667. * Implementation of the DDS Texture Loader.
  89668. */
  89669. var DDSTextureLoader = /** @class */ (function () {
  89670. function DDSTextureLoader() {
  89671. /**
  89672. * Defines wether the loader supports cascade loading the different faces.
  89673. */
  89674. this.supportCascades = true;
  89675. }
  89676. /**
  89677. * This returns if the loader support the current file information.
  89678. * @param extension defines the file extension of the file being loaded
  89679. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89680. * @param fallback defines the fallback internal texture if any
  89681. * @param isBase64 defines whether the texture is encoded as a base64
  89682. * @param isBuffer defines whether the texture data are stored as a buffer
  89683. * @returns true if the loader can load the specified file
  89684. */
  89685. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89686. return extension.indexOf(".dds") === 0;
  89687. };
  89688. /**
  89689. * Transform the url before loading if required.
  89690. * @param rootUrl the url of the texture
  89691. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89692. * @returns the transformed texture
  89693. */
  89694. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89695. return rootUrl;
  89696. };
  89697. /**
  89698. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89699. * @param rootUrl the url of the texture
  89700. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89701. * @returns the fallback texture
  89702. */
  89703. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89704. return null;
  89705. };
  89706. /**
  89707. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89708. * @param data contains the texture data
  89709. * @param texture defines the BabylonJS internal texture
  89710. * @param createPolynomials will be true if polynomials have been requested
  89711. * @param onLoad defines the callback to trigger once the texture is ready
  89712. * @param onError defines the callback to trigger in case of error
  89713. */
  89714. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  89715. var engine = texture.getEngine();
  89716. var info;
  89717. var loadMipmap = false;
  89718. if (Array.isArray(imgs)) {
  89719. for (var index = 0; index < imgs.length; index++) {
  89720. var data_1 = imgs[index];
  89721. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  89722. texture.width = info.width;
  89723. texture.height = info.height;
  89724. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89725. engine._unpackFlipY(info.isCompressed);
  89726. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  89727. if (!info.isFourCC && info.mipmapCount === 1) {
  89728. engine.generateMipMapsForCubemap(texture);
  89729. }
  89730. }
  89731. }
  89732. else {
  89733. var data = imgs;
  89734. info = BABYLON.DDSTools.GetDDSInfo(data);
  89735. texture.width = info.width;
  89736. texture.height = info.height;
  89737. if (createPolynomials) {
  89738. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  89739. }
  89740. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89741. engine._unpackFlipY(info.isCompressed);
  89742. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  89743. if (!info.isFourCC && info.mipmapCount === 1) {
  89744. engine.generateMipMapsForCubemap(texture);
  89745. }
  89746. }
  89747. engine._setCubeMapTextureParams(loadMipmap);
  89748. texture.isReady = true;
  89749. if (onLoad) {
  89750. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  89751. }
  89752. };
  89753. /**
  89754. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89755. * @param data contains the texture data
  89756. * @param texture defines the BabylonJS internal texture
  89757. * @param callback defines the method to call once ready to upload
  89758. */
  89759. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  89760. var info = BABYLON.DDSTools.GetDDSInfo(data);
  89761. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  89762. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  89763. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  89764. });
  89765. };
  89766. return DDSTextureLoader;
  89767. }());
  89768. // Register the loader.
  89769. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  89770. })(BABYLON || (BABYLON = {}));
  89771. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  89772. var BABYLON;
  89773. (function (BABYLON) {
  89774. /*
  89775. * Based on jsTGALoader - Javascript loader for TGA file
  89776. * By Vincent Thibault
  89777. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  89778. */
  89779. var TGATools = /** @class */ (function () {
  89780. function TGATools() {
  89781. }
  89782. TGATools.GetTGAHeader = function (data) {
  89783. var offset = 0;
  89784. var header = {
  89785. id_length: data[offset++],
  89786. colormap_type: data[offset++],
  89787. image_type: data[offset++],
  89788. colormap_index: data[offset++] | data[offset++] << 8,
  89789. colormap_length: data[offset++] | data[offset++] << 8,
  89790. colormap_size: data[offset++],
  89791. origin: [
  89792. data[offset++] | data[offset++] << 8,
  89793. data[offset++] | data[offset++] << 8
  89794. ],
  89795. width: data[offset++] | data[offset++] << 8,
  89796. height: data[offset++] | data[offset++] << 8,
  89797. pixel_size: data[offset++],
  89798. flags: data[offset++]
  89799. };
  89800. return header;
  89801. };
  89802. /**
  89803. * Uploads TGA content to a Babylon Texture
  89804. * @hidden
  89805. */
  89806. TGATools.UploadContent = function (texture, data) {
  89807. // Not enough data to contain header ?
  89808. if (data.length < 19) {
  89809. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  89810. return;
  89811. }
  89812. // Read Header
  89813. var offset = 18;
  89814. var header = TGATools.GetTGAHeader(data);
  89815. // Assume it's a valid Targa file.
  89816. if (header.id_length + offset > data.length) {
  89817. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  89818. return;
  89819. }
  89820. // Skip not needed data
  89821. offset += header.id_length;
  89822. var use_rle = false;
  89823. var use_pal = false;
  89824. var use_grey = false;
  89825. // Get some informations.
  89826. switch (header.image_type) {
  89827. case TGATools._TYPE_RLE_INDEXED:
  89828. use_rle = true;
  89829. case TGATools._TYPE_INDEXED:
  89830. use_pal = true;
  89831. break;
  89832. case TGATools._TYPE_RLE_RGB:
  89833. use_rle = true;
  89834. case TGATools._TYPE_RGB:
  89835. // use_rgb = true;
  89836. break;
  89837. case TGATools._TYPE_RLE_GREY:
  89838. use_rle = true;
  89839. case TGATools._TYPE_GREY:
  89840. use_grey = true;
  89841. break;
  89842. }
  89843. var pixel_data;
  89844. // var numAlphaBits = header.flags & 0xf;
  89845. var pixel_size = header.pixel_size >> 3;
  89846. var pixel_total = header.width * header.height * pixel_size;
  89847. // Read palettes
  89848. var palettes;
  89849. if (use_pal) {
  89850. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  89851. }
  89852. // Read LRE
  89853. if (use_rle) {
  89854. pixel_data = new Uint8Array(pixel_total);
  89855. var c, count, i;
  89856. var localOffset = 0;
  89857. var pixels = new Uint8Array(pixel_size);
  89858. while (offset < pixel_total && localOffset < pixel_total) {
  89859. c = data[offset++];
  89860. count = (c & 0x7f) + 1;
  89861. // RLE pixels
  89862. if (c & 0x80) {
  89863. // Bind pixel tmp array
  89864. for (i = 0; i < pixel_size; ++i) {
  89865. pixels[i] = data[offset++];
  89866. }
  89867. // Copy pixel array
  89868. for (i = 0; i < count; ++i) {
  89869. pixel_data.set(pixels, localOffset + i * pixel_size);
  89870. }
  89871. localOffset += pixel_size * count;
  89872. }
  89873. // Raw pixels
  89874. else {
  89875. count *= pixel_size;
  89876. for (i = 0; i < count; ++i) {
  89877. pixel_data[localOffset + i] = data[offset++];
  89878. }
  89879. localOffset += count;
  89880. }
  89881. }
  89882. }
  89883. // RAW Pixels
  89884. else {
  89885. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  89886. }
  89887. // Load to texture
  89888. var x_start, y_start, x_step, y_step, y_end, x_end;
  89889. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  89890. default:
  89891. case TGATools._ORIGIN_UL:
  89892. x_start = 0;
  89893. x_step = 1;
  89894. x_end = header.width;
  89895. y_start = 0;
  89896. y_step = 1;
  89897. y_end = header.height;
  89898. break;
  89899. case TGATools._ORIGIN_BL:
  89900. x_start = 0;
  89901. x_step = 1;
  89902. x_end = header.width;
  89903. y_start = header.height - 1;
  89904. y_step = -1;
  89905. y_end = -1;
  89906. break;
  89907. case TGATools._ORIGIN_UR:
  89908. x_start = header.width - 1;
  89909. x_step = -1;
  89910. x_end = -1;
  89911. y_start = 0;
  89912. y_step = 1;
  89913. y_end = header.height;
  89914. break;
  89915. case TGATools._ORIGIN_BR:
  89916. x_start = header.width - 1;
  89917. x_step = -1;
  89918. x_end = -1;
  89919. y_start = header.height - 1;
  89920. y_step = -1;
  89921. y_end = -1;
  89922. break;
  89923. }
  89924. // Load the specify method
  89925. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  89926. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  89927. var engine = texture.getEngine();
  89928. engine._uploadDataToTextureDirectly(texture, imageData);
  89929. };
  89930. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89931. var image = pixel_data, colormap = palettes;
  89932. var width = header.width, height = header.height;
  89933. var color, i = 0, x, y;
  89934. var imageData = new Uint8Array(width * height * 4);
  89935. for (y = y_start; y !== y_end; y += y_step) {
  89936. for (x = x_start; x !== x_end; x += x_step, i++) {
  89937. color = image[i];
  89938. imageData[(x + width * y) * 4 + 3] = 255;
  89939. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  89940. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  89941. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  89942. }
  89943. }
  89944. return imageData;
  89945. };
  89946. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89947. var image = pixel_data;
  89948. var width = header.width, height = header.height;
  89949. var color, i = 0, x, y;
  89950. var imageData = new Uint8Array(width * height * 4);
  89951. for (y = y_start; y !== y_end; y += y_step) {
  89952. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89953. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  89954. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  89955. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  89956. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  89957. imageData[(x + width * y) * 4 + 0] = r;
  89958. imageData[(x + width * y) * 4 + 1] = g;
  89959. imageData[(x + width * y) * 4 + 2] = b;
  89960. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  89961. }
  89962. }
  89963. return imageData;
  89964. };
  89965. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89966. var image = pixel_data;
  89967. var width = header.width, height = header.height;
  89968. var i = 0, x, y;
  89969. var imageData = new Uint8Array(width * height * 4);
  89970. for (y = y_start; y !== y_end; y += y_step) {
  89971. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  89972. imageData[(x + width * y) * 4 + 3] = 255;
  89973. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89974. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89975. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89976. }
  89977. }
  89978. return imageData;
  89979. };
  89980. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89981. var image = pixel_data;
  89982. var width = header.width, height = header.height;
  89983. var i = 0, x, y;
  89984. var imageData = new Uint8Array(width * height * 4);
  89985. for (y = y_start; y !== y_end; y += y_step) {
  89986. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  89987. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89988. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89989. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89990. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  89991. }
  89992. }
  89993. return imageData;
  89994. };
  89995. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89996. var image = pixel_data;
  89997. var width = header.width, height = header.height;
  89998. var color, i = 0, x, y;
  89999. var imageData = new Uint8Array(width * height * 4);
  90000. for (y = y_start; y !== y_end; y += y_step) {
  90001. for (x = x_start; x !== x_end; x += x_step, i++) {
  90002. color = image[i];
  90003. imageData[(x + width * y) * 4 + 0] = color;
  90004. imageData[(x + width * y) * 4 + 1] = color;
  90005. imageData[(x + width * y) * 4 + 2] = color;
  90006. imageData[(x + width * y) * 4 + 3] = 255;
  90007. }
  90008. }
  90009. return imageData;
  90010. };
  90011. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  90012. var image = pixel_data;
  90013. var width = header.width, height = header.height;
  90014. var i = 0, x, y;
  90015. var imageData = new Uint8Array(width * height * 4);
  90016. for (y = y_start; y !== y_end; y += y_step) {
  90017. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  90018. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  90019. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  90020. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  90021. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  90022. }
  90023. }
  90024. return imageData;
  90025. };
  90026. //private static _TYPE_NO_DATA = 0;
  90027. TGATools._TYPE_INDEXED = 1;
  90028. TGATools._TYPE_RGB = 2;
  90029. TGATools._TYPE_GREY = 3;
  90030. TGATools._TYPE_RLE_INDEXED = 9;
  90031. TGATools._TYPE_RLE_RGB = 10;
  90032. TGATools._TYPE_RLE_GREY = 11;
  90033. TGATools._ORIGIN_MASK = 0x30;
  90034. TGATools._ORIGIN_SHIFT = 0x04;
  90035. TGATools._ORIGIN_BL = 0x00;
  90036. TGATools._ORIGIN_BR = 0x01;
  90037. TGATools._ORIGIN_UL = 0x02;
  90038. TGATools._ORIGIN_UR = 0x03;
  90039. return TGATools;
  90040. }());
  90041. BABYLON.TGATools = TGATools;
  90042. })(BABYLON || (BABYLON = {}));
  90043. //# sourceMappingURL=babylon.tga.js.map
  90044. var BABYLON;
  90045. (function (BABYLON) {
  90046. /**
  90047. * Implementation of the TGA Texture Loader.
  90048. */
  90049. var TGATextureLoader = /** @class */ (function () {
  90050. function TGATextureLoader() {
  90051. /**
  90052. * Defines wether the loader supports cascade loading the different faces.
  90053. */
  90054. this.supportCascades = false;
  90055. }
  90056. /**
  90057. * This returns if the loader support the current file information.
  90058. * @param extension defines the file extension of the file being loaded
  90059. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90060. * @param fallback defines the fallback internal texture if any
  90061. * @param isBase64 defines whether the texture is encoded as a base64
  90062. * @param isBuffer defines whether the texture data are stored as a buffer
  90063. * @returns true if the loader can load the specified file
  90064. */
  90065. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90066. return extension.indexOf(".tga") === 0;
  90067. };
  90068. /**
  90069. * Transform the url before loading if required.
  90070. * @param rootUrl the url of the texture
  90071. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90072. * @returns the transformed texture
  90073. */
  90074. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90075. return rootUrl;
  90076. };
  90077. /**
  90078. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90079. * @param rootUrl the url of the texture
  90080. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90081. * @returns the fallback texture
  90082. */
  90083. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90084. return null;
  90085. };
  90086. /**
  90087. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90088. * @param data contains the texture data
  90089. * @param texture defines the BabylonJS internal texture
  90090. * @param createPolynomials will be true if polynomials have been requested
  90091. * @param onLoad defines the callback to trigger once the texture is ready
  90092. * @param onError defines the callback to trigger in case of error
  90093. */
  90094. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90095. throw ".env not supported in Cube.";
  90096. };
  90097. /**
  90098. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90099. * @param data contains the texture data
  90100. * @param texture defines the BabylonJS internal texture
  90101. * @param callback defines the method to call once ready to upload
  90102. */
  90103. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  90104. var uintData = new Uint8Array(data);
  90105. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  90106. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  90107. BABYLON.TGATools.UploadContent(texture, uintData);
  90108. });
  90109. };
  90110. return TGATextureLoader;
  90111. }());
  90112. // Register the loader.
  90113. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  90114. })(BABYLON || (BABYLON = {}));
  90115. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  90116. var BABYLON;
  90117. (function (BABYLON) {
  90118. /**
  90119. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  90120. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  90121. */
  90122. var KhronosTextureContainer = /** @class */ (function () {
  90123. /**
  90124. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  90125. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  90126. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  90127. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  90128. */
  90129. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  90130. this.arrayBuffer = arrayBuffer;
  90131. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  90132. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  90133. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  90134. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  90135. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  90136. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  90137. BABYLON.Tools.Error("texture missing KTX identifier");
  90138. return;
  90139. }
  90140. // load the reset of the header in native 32 bit int
  90141. var header = new Int32Array(this.arrayBuffer, 12, 13);
  90142. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  90143. var oppositeEndianess = header[0] === 0x01020304;
  90144. // read all the header elements in order they exist in the file, without modification (sans endainness)
  90145. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  90146. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  90147. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  90148. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  90149. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  90150. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  90151. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  90152. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  90153. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  90154. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  90155. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  90156. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  90157. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  90158. if (this.glType !== 0) {
  90159. BABYLON.Tools.Error("only compressed formats currently supported");
  90160. return;
  90161. }
  90162. else {
  90163. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  90164. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  90165. }
  90166. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  90167. BABYLON.Tools.Error("only 2D textures currently supported");
  90168. return;
  90169. }
  90170. if (this.numberOfArrayElements !== 0) {
  90171. BABYLON.Tools.Error("texture arrays not currently supported");
  90172. return;
  90173. }
  90174. if (this.numberOfFaces !== facesExpected) {
  90175. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  90176. return;
  90177. }
  90178. // we now have a completely validated file, so could use existence of loadType as success
  90179. // would need to make this more elaborate & adjust checks above to support more than one load type
  90180. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  90181. }
  90182. // not as fast hardware based, but will probably never need to use
  90183. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  90184. return ((val & 0xFF) << 24)
  90185. | ((val & 0xFF00) << 8)
  90186. | ((val >> 8) & 0xFF00)
  90187. | ((val >> 24) & 0xFF);
  90188. };
  90189. /**
  90190. * Uploads KTX content to a Babylon Texture.
  90191. * It is assumed that the texture has already been created & is currently bound
  90192. * @hidden
  90193. */
  90194. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  90195. switch (this.loadType) {
  90196. case KhronosTextureContainer.COMPRESSED_2D:
  90197. this._upload2DCompressedLevels(texture, loadMipmaps);
  90198. break;
  90199. case KhronosTextureContainer.TEX_2D:
  90200. case KhronosTextureContainer.COMPRESSED_3D:
  90201. case KhronosTextureContainer.TEX_3D:
  90202. }
  90203. };
  90204. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  90205. // initialize width & height for level 1
  90206. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  90207. var width = this.pixelWidth;
  90208. var height = this.pixelHeight;
  90209. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  90210. for (var level = 0; level < mipmapCount; level++) {
  90211. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  90212. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  90213. for (var face = 0; face < this.numberOfFaces; face++) {
  90214. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  90215. var engine = texture.getEngine();
  90216. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  90217. dataOffset += imageSize; // add size of the image for the next face/mipmap
  90218. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  90219. }
  90220. width = Math.max(1.0, width * 0.5);
  90221. height = Math.max(1.0, height * 0.5);
  90222. }
  90223. };
  90224. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  90225. // load types
  90226. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  90227. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  90228. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  90229. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  90230. return KhronosTextureContainer;
  90231. }());
  90232. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  90233. })(BABYLON || (BABYLON = {}));
  90234. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  90235. var BABYLON;
  90236. (function (BABYLON) {
  90237. /**
  90238. * Implementation of the KTX Texture Loader.
  90239. */
  90240. var KTXTextureLoader = /** @class */ (function () {
  90241. function KTXTextureLoader() {
  90242. /**
  90243. * Defines wether the loader supports cascade loading the different faces.
  90244. */
  90245. this.supportCascades = false;
  90246. }
  90247. /**
  90248. * This returns if the loader support the current file information.
  90249. * @param extension defines the file extension of the file being loaded
  90250. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90251. * @param fallback defines the fallback internal texture if any
  90252. * @param isBase64 defines whether the texture is encoded as a base64
  90253. * @param isBuffer defines whether the texture data are stored as a buffer
  90254. * @returns true if the loader can load the specified file
  90255. */
  90256. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90257. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  90258. return true;
  90259. }
  90260. return false;
  90261. };
  90262. /**
  90263. * Transform the url before loading if required.
  90264. * @param rootUrl the url of the texture
  90265. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90266. * @returns the transformed texture
  90267. */
  90268. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90269. var lastDot = rootUrl.lastIndexOf('.');
  90270. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  90271. };
  90272. /**
  90273. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90274. * @param rootUrl the url of the texture
  90275. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90276. * @returns the fallback texture
  90277. */
  90278. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90279. // remove the format appended to the rootUrl in the original createCubeTexture call.
  90280. var exp = new RegExp("" + textureFormatInUse + "$");
  90281. return rootUrl.replace(exp, "");
  90282. };
  90283. /**
  90284. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90285. * @param data contains the texture data
  90286. * @param texture defines the BabylonJS internal texture
  90287. * @param createPolynomials will be true if polynomials have been requested
  90288. * @param onLoad defines the callback to trigger once the texture is ready
  90289. * @param onError defines the callback to trigger in case of error
  90290. */
  90291. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90292. if (Array.isArray(data)) {
  90293. return;
  90294. }
  90295. var engine = texture.getEngine();
  90296. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  90297. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  90298. engine._unpackFlipY(true);
  90299. ktx.uploadLevels(texture, texture.generateMipMaps);
  90300. texture.width = ktx.pixelWidth;
  90301. texture.height = ktx.pixelHeight;
  90302. engine._setCubeMapTextureParams(loadMipmap);
  90303. texture.isReady = true;
  90304. };
  90305. /**
  90306. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90307. * @param data contains the texture data
  90308. * @param texture defines the BabylonJS internal texture
  90309. * @param callback defines the method to call once ready to upload
  90310. */
  90311. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  90312. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  90313. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  90314. ktx.uploadLevels(texture, texture.generateMipMaps);
  90315. });
  90316. };
  90317. return KTXTextureLoader;
  90318. }());
  90319. // Register the loader.
  90320. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  90321. })(BABYLON || (BABYLON = {}));
  90322. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  90323. var BABYLON;
  90324. (function (BABYLON) {
  90325. /**
  90326. * Sets of helpers addressing the serialization and deserialization of environment texture
  90327. * stored in a BabylonJS env file.
  90328. * Those files are usually stored as .env files.
  90329. */
  90330. var EnvironmentTextureTools = /** @class */ (function () {
  90331. function EnvironmentTextureTools() {
  90332. }
  90333. /**
  90334. * Gets the environment info from an env file.
  90335. * @param data The array buffer containing the .env bytes.
  90336. * @returns the environment file info (the json header) if successfully parsed.
  90337. */
  90338. EnvironmentTextureTools.GetEnvInfo = function (data) {
  90339. var dataView = new DataView(data);
  90340. var pos = 0;
  90341. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90342. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  90343. BABYLON.Tools.Error('Not a babylon environment map');
  90344. return null;
  90345. }
  90346. }
  90347. // Read json manifest - collect characters up to null terminator
  90348. var manifestString = '';
  90349. var charCode = 0x00;
  90350. while ((charCode = dataView.getUint8(pos++))) {
  90351. manifestString += String.fromCharCode(charCode);
  90352. }
  90353. var manifest = JSON.parse(manifestString);
  90354. if (manifest.specular) {
  90355. // Extend the header with the position of the payload.
  90356. manifest.specular.specularDataPosition = pos;
  90357. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  90358. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  90359. }
  90360. return manifest;
  90361. };
  90362. /**
  90363. * Creates an environment texture from a loaded cube texture.
  90364. * @param texture defines the cube texture to convert in env file
  90365. * @return a promise containing the environment data if succesfull.
  90366. */
  90367. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  90368. var _this = this;
  90369. var internalTexture = texture.getInternalTexture();
  90370. if (!internalTexture) {
  90371. return Promise.reject("The cube texture is invalid.");
  90372. }
  90373. if (!texture._prefiltered) {
  90374. return Promise.reject("The cube texture is invalid (not prefiltered).");
  90375. }
  90376. var engine = internalTexture.getEngine();
  90377. if (engine && engine.premultipliedAlpha) {
  90378. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  90379. }
  90380. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  90381. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  90382. }
  90383. var canvas = engine.getRenderingCanvas();
  90384. if (!canvas) {
  90385. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  90386. }
  90387. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90388. if (!engine.getCaps().textureFloatRender) {
  90389. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90390. if (!engine.getCaps().textureHalfFloatRender) {
  90391. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  90392. }
  90393. }
  90394. var cubeWidth = internalTexture.width;
  90395. var hostingScene = new BABYLON.Scene(engine);
  90396. var specularTextures = {};
  90397. var promises = [];
  90398. // Read and collect all mipmaps data from the cube.
  90399. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  90400. mipmapsCount = Math.round(mipmapsCount);
  90401. var _loop_1 = function (i) {
  90402. var faceWidth = Math.pow(2, mipmapsCount - i);
  90403. var _loop_2 = function (face) {
  90404. var data = texture.readPixels(face, i);
  90405. // Creates a temp texture with the face data.
  90406. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  90407. // And rgbdEncode them.
  90408. var promise = new Promise(function (resolve, reject) {
  90409. 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);
  90410. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90411. rgbdPostProcess.onApply = function (effect) {
  90412. effect._bindTexture("textureSampler", tempTexture);
  90413. };
  90414. // As the process needs to happen on the main canvas, keep track of the current size
  90415. var currentW = engine.getRenderWidth();
  90416. var currentH = engine.getRenderHeight();
  90417. // Set the desired size for the texture
  90418. engine.setSize(faceWidth, faceWidth);
  90419. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  90420. // Reading datas from WebGL
  90421. BABYLON.Tools.ToBlob(canvas, function (blob) {
  90422. var fileReader = new FileReader();
  90423. fileReader.onload = function (event) {
  90424. var arrayBuffer = event.target.result;
  90425. specularTextures[i * 6 + face] = arrayBuffer;
  90426. resolve();
  90427. };
  90428. fileReader.readAsArrayBuffer(blob);
  90429. });
  90430. // Reapply the previous canvas size
  90431. engine.setSize(currentW, currentH);
  90432. });
  90433. });
  90434. promises.push(promise);
  90435. };
  90436. // All faces of the cube.
  90437. for (var face = 0; face < 6; face++) {
  90438. _loop_2(face);
  90439. }
  90440. };
  90441. for (var i = 0; i <= mipmapsCount; i++) {
  90442. _loop_1(i);
  90443. }
  90444. // Once all the textures haves been collected as RGBD stored in PNGs
  90445. return Promise.all(promises).then(function () {
  90446. // We can delete the hosting scene keeping track of all the creation objects
  90447. hostingScene.dispose();
  90448. // Creates the json header for the env texture
  90449. var info = {
  90450. version: 1,
  90451. width: cubeWidth,
  90452. irradiance: _this._CreateEnvTextureIrradiance(texture),
  90453. specular: {
  90454. mipmaps: [],
  90455. lodGenerationScale: texture.lodGenerationScale
  90456. }
  90457. };
  90458. // Sets the specular image data information
  90459. var position = 0;
  90460. for (var i = 0; i <= mipmapsCount; i++) {
  90461. for (var face = 0; face < 6; face++) {
  90462. var byteLength = specularTextures[i * 6 + face].byteLength;
  90463. info.specular.mipmaps.push({
  90464. length: byteLength,
  90465. position: position
  90466. });
  90467. position += byteLength;
  90468. }
  90469. }
  90470. // Encode the JSON as an array buffer
  90471. var infoString = JSON.stringify(info);
  90472. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  90473. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  90474. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  90475. infoView[i] = infoString.charCodeAt(i);
  90476. }
  90477. // Ends up with a null terminator for easier parsing
  90478. infoView[infoString.length] = 0x00;
  90479. // Computes the final required size and creates the storage
  90480. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  90481. var finalBuffer = new ArrayBuffer(totalSize);
  90482. var finalBufferView = new Uint8Array(finalBuffer);
  90483. var dataView = new DataView(finalBuffer);
  90484. // Copy the magic bytes identifying the file in
  90485. var pos = 0;
  90486. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  90487. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  90488. }
  90489. // Add the json info
  90490. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  90491. pos += infoBuffer.byteLength;
  90492. // Finally inserts the texture data
  90493. for (var i = 0; i <= mipmapsCount; i++) {
  90494. for (var face = 0; face < 6; face++) {
  90495. var dataBuffer = specularTextures[i * 6 + face];
  90496. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  90497. pos += dataBuffer.byteLength;
  90498. }
  90499. }
  90500. // Voila
  90501. return finalBuffer;
  90502. });
  90503. };
  90504. /**
  90505. * Creates a JSON representation of the spherical data.
  90506. * @param texture defines the texture containing the polynomials
  90507. * @return the JSON representation of the spherical info
  90508. */
  90509. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  90510. var polynmials = texture.sphericalPolynomial;
  90511. if (polynmials == null) {
  90512. return null;
  90513. }
  90514. return {
  90515. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  90516. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  90517. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  90518. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  90519. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  90520. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  90521. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  90522. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  90523. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  90524. };
  90525. };
  90526. /**
  90527. * Uploads the texture info contained in the env file to the GPU.
  90528. * @param texture defines the internal texture to upload to
  90529. * @param arrayBuffer defines the buffer cotaining the data to load
  90530. * @param info defines the texture info retrieved through the GetEnvInfo method
  90531. * @returns a promise
  90532. */
  90533. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  90534. if (info.version !== 1) {
  90535. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  90536. }
  90537. var specularInfo = info.specular;
  90538. if (!specularInfo) {
  90539. // Nothing else parsed so far
  90540. return Promise.resolve();
  90541. }
  90542. // Double checks the enclosed info
  90543. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  90544. mipmapsCount = Math.round(mipmapsCount) + 1;
  90545. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  90546. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  90547. }
  90548. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  90549. var imageData = new Array(mipmapsCount);
  90550. for (var i = 0; i < mipmapsCount; i++) {
  90551. imageData[i] = new Array(6);
  90552. for (var face = 0; face < 6; face++) {
  90553. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  90554. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  90555. }
  90556. }
  90557. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  90558. };
  90559. /**
  90560. * Uploads the levels of image data to the GPU.
  90561. * @param texture defines the internal texture to upload to
  90562. * @param imageData defines the array buffer views of image data [mipmap][face]
  90563. * @returns a promise
  90564. */
  90565. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  90566. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  90567. throw new Error("Texture size must be a power of two");
  90568. }
  90569. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  90570. // Gets everything ready.
  90571. var engine = texture.getEngine();
  90572. var expandTexture = false;
  90573. var generateNonLODTextures = false;
  90574. var rgbdPostProcess = null;
  90575. var cubeRtt = null;
  90576. var lodTextures = null;
  90577. var caps = engine.getCaps();
  90578. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90579. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90580. texture.generateMipMaps = true;
  90581. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  90582. // Add extra process if texture lod is not supported
  90583. if (!caps.textureLOD) {
  90584. expandTexture = false;
  90585. generateNonLODTextures = true;
  90586. lodTextures = {};
  90587. }
  90588. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  90589. else if (engine.webGLVersion < 2) {
  90590. expandTexture = false;
  90591. }
  90592. // If half float available we can uncompress the texture
  90593. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  90594. expandTexture = true;
  90595. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90596. }
  90597. // If full float available we can uncompress the texture
  90598. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  90599. expandTexture = true;
  90600. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90601. }
  90602. // Expand the texture if possible
  90603. if (expandTexture) {
  90604. // Simply run through the decode PP
  90605. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  90606. texture._isRGBD = false;
  90607. texture.invertY = false;
  90608. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  90609. generateDepthBuffer: false,
  90610. generateMipMaps: true,
  90611. generateStencilBuffer: false,
  90612. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  90613. type: texture.type,
  90614. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  90615. });
  90616. }
  90617. else {
  90618. texture._isRGBD = true;
  90619. texture.invertY = true;
  90620. // In case of missing support, applies the same patch than DDS files.
  90621. if (generateNonLODTextures) {
  90622. var mipSlices = 3;
  90623. var scale = texture._lodGenerationScale;
  90624. var offset = texture._lodGenerationOffset;
  90625. for (var i = 0; i < mipSlices; i++) {
  90626. //compute LOD from even spacing in smoothness (matching shader calculation)
  90627. var smoothness = i / (mipSlices - 1);
  90628. var roughness = 1 - smoothness;
  90629. var minLODIndex = offset; // roughness = 0
  90630. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  90631. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  90632. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  90633. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  90634. glTextureFromLod.isCube = true;
  90635. glTextureFromLod.invertY = true;
  90636. glTextureFromLod.generateMipMaps = false;
  90637. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  90638. // Wrap in a base texture for easy binding.
  90639. var lodTexture = new BABYLON.BaseTexture(null);
  90640. lodTexture.isCube = true;
  90641. lodTexture._texture = glTextureFromLod;
  90642. lodTextures[mipmapIndex] = lodTexture;
  90643. switch (i) {
  90644. case 0:
  90645. texture._lodTextureLow = lodTexture;
  90646. break;
  90647. case 1:
  90648. texture._lodTextureMid = lodTexture;
  90649. break;
  90650. case 2:
  90651. texture._lodTextureHigh = lodTexture;
  90652. break;
  90653. }
  90654. }
  90655. }
  90656. }
  90657. var promises = [];
  90658. var _loop_3 = function (i) {
  90659. var _loop_4 = function (face) {
  90660. // Constructs an image element from image data
  90661. var bytes = imageData[i][face];
  90662. var blob = new Blob([bytes], { type: 'image/png' });
  90663. var url = URL.createObjectURL(blob);
  90664. var image = new Image();
  90665. image.src = url;
  90666. // Enqueue promise to upload to the texture.
  90667. var promise = new Promise(function (resolve, reject) {
  90668. image.onload = function () {
  90669. if (expandTexture) {
  90670. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  90671. reject(message);
  90672. }, image);
  90673. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90674. // Uncompress the data to a RTT
  90675. rgbdPostProcess.onApply = function (effect) {
  90676. effect._bindTexture("textureSampler", tempTexture_1);
  90677. effect.setFloat2("scale", 1, 1);
  90678. };
  90679. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  90680. // Cleanup
  90681. engine.restoreDefaultFramebuffer();
  90682. tempTexture_1.dispose();
  90683. window.URL.revokeObjectURL(url);
  90684. resolve();
  90685. });
  90686. }
  90687. else {
  90688. engine._uploadImageToTexture(texture, image, face, i);
  90689. // Upload the face to the non lod texture support
  90690. if (generateNonLODTextures) {
  90691. var lodTexture = lodTextures[i];
  90692. if (lodTexture) {
  90693. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  90694. }
  90695. }
  90696. resolve();
  90697. }
  90698. };
  90699. image.onerror = function (error) {
  90700. reject(error);
  90701. };
  90702. });
  90703. promises.push(promise);
  90704. };
  90705. // All faces
  90706. for (var face = 0; face < 6; face++) {
  90707. _loop_4(face);
  90708. }
  90709. };
  90710. // All mipmaps up to provided number of images
  90711. for (var i = 0; i < imageData.length; i++) {
  90712. _loop_3(i);
  90713. }
  90714. // Fill remaining mipmaps with black textures.
  90715. if (imageData.length < mipmapsCount) {
  90716. var data = void 0;
  90717. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  90718. var dataLength = size * size * 4;
  90719. switch (texture.type) {
  90720. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  90721. data = new Uint8Array(dataLength);
  90722. break;
  90723. }
  90724. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  90725. data = new Uint16Array(dataLength);
  90726. break;
  90727. }
  90728. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  90729. data = new Float32Array(dataLength);
  90730. break;
  90731. }
  90732. }
  90733. for (var i = imageData.length; i < mipmapsCount; i++) {
  90734. for (var face = 0; face < 6; face++) {
  90735. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  90736. }
  90737. }
  90738. }
  90739. // Once all done, finishes the cleanup and return
  90740. return Promise.all(promises).then(function () {
  90741. // Release temp RTT.
  90742. if (cubeRtt) {
  90743. engine._releaseFramebufferObjects(cubeRtt);
  90744. cubeRtt._swapAndDie(texture);
  90745. }
  90746. // Release temp Post Process.
  90747. if (rgbdPostProcess) {
  90748. rgbdPostProcess.dispose();
  90749. }
  90750. // Flag internal texture as ready in case they are in use.
  90751. if (generateNonLODTextures) {
  90752. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  90753. texture._lodTextureHigh._texture.isReady = true;
  90754. }
  90755. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  90756. texture._lodTextureMid._texture.isReady = true;
  90757. }
  90758. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  90759. texture._lodTextureLow._texture.isReady = true;
  90760. }
  90761. }
  90762. });
  90763. };
  90764. /**
  90765. * Uploads spherical polynomials information to the texture.
  90766. * @param texture defines the texture we are trying to upload the information to
  90767. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  90768. */
  90769. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  90770. if (info.version !== 1) {
  90771. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  90772. }
  90773. var irradianceInfo = info.irradiance;
  90774. if (!irradianceInfo) {
  90775. return;
  90776. }
  90777. var sp = new BABYLON.SphericalPolynomial();
  90778. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  90779. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  90780. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  90781. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  90782. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  90783. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  90784. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  90785. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  90786. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  90787. texture._sphericalPolynomial = sp;
  90788. };
  90789. /**
  90790. * Magic number identifying the env file.
  90791. */
  90792. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  90793. return EnvironmentTextureTools;
  90794. }());
  90795. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  90796. })(BABYLON || (BABYLON = {}));
  90797. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  90798. var BABYLON;
  90799. (function (BABYLON) {
  90800. /**
  90801. * Implementation of the ENV Texture Loader.
  90802. */
  90803. var ENVTextureLoader = /** @class */ (function () {
  90804. function ENVTextureLoader() {
  90805. /**
  90806. * Defines wether the loader supports cascade loading the different faces.
  90807. */
  90808. this.supportCascades = false;
  90809. }
  90810. /**
  90811. * This returns if the loader support the current file information.
  90812. * @param extension defines the file extension of the file being loaded
  90813. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90814. * @param fallback defines the fallback internal texture if any
  90815. * @param isBase64 defines whether the texture is encoded as a base64
  90816. * @param isBuffer defines whether the texture data are stored as a buffer
  90817. * @returns true if the loader can load the specified file
  90818. */
  90819. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90820. return extension.indexOf(".env") === 0;
  90821. };
  90822. /**
  90823. * Transform the url before loading if required.
  90824. * @param rootUrl the url of the texture
  90825. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90826. * @returns the transformed texture
  90827. */
  90828. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90829. return rootUrl;
  90830. };
  90831. /**
  90832. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90833. * @param rootUrl the url of the texture
  90834. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90835. * @returns the fallback texture
  90836. */
  90837. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90838. return null;
  90839. };
  90840. /**
  90841. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90842. * @param data contains the texture data
  90843. * @param texture defines the BabylonJS internal texture
  90844. * @param createPolynomials will be true if polynomials have been requested
  90845. * @param onLoad defines the callback to trigger once the texture is ready
  90846. * @param onError defines the callback to trigger in case of error
  90847. */
  90848. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90849. if (Array.isArray(data)) {
  90850. return;
  90851. }
  90852. data = data;
  90853. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  90854. if (info) {
  90855. texture.width = info.width;
  90856. texture.height = info.width;
  90857. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  90858. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  90859. texture.isReady = true;
  90860. if (onLoad) {
  90861. onLoad();
  90862. }
  90863. });
  90864. }
  90865. else if (onError) {
  90866. onError("Can not parse the environment file", null);
  90867. }
  90868. };
  90869. /**
  90870. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90871. * @param data contains the texture data
  90872. * @param texture defines the BabylonJS internal texture
  90873. * @param callback defines the method to call once ready to upload
  90874. */
  90875. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  90876. throw ".env not supported in 2d.";
  90877. };
  90878. return ENVTextureLoader;
  90879. }());
  90880. // Register the loader.
  90881. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  90882. })(BABYLON || (BABYLON = {}));
  90883. //# sourceMappingURL=babylon.envTextureLoader.js.map
  90884. var BABYLON;
  90885. (function (BABYLON) {
  90886. /**
  90887. * Renders a layer on top of an existing scene
  90888. */
  90889. var UtilityLayerRenderer = /** @class */ (function () {
  90890. /**
  90891. * Instantiates a UtilityLayerRenderer
  90892. * @param originalScene the original scene that will be rendered on top of
  90893. */
  90894. function UtilityLayerRenderer(
  90895. /** the original scene that will be rendered on top of */
  90896. originalScene) {
  90897. var _this = this;
  90898. this.originalScene = originalScene;
  90899. this._pointerCaptures = {};
  90900. this._lastPointerEvents = {};
  90901. /**
  90902. * If the utility layer should automatically be rendered on top of existing scene
  90903. */
  90904. this.shouldRender = true;
  90905. /**
  90906. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  90907. */
  90908. this.onlyCheckPointerDownEvents = true;
  90909. /**
  90910. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  90911. */
  90912. this.processAllEvents = false;
  90913. /**
  90914. * Observable raised when the pointer move from the utility layer scene to the main scene
  90915. */
  90916. this.onPointerOutObservable = new BABYLON.Observable();
  90917. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  90918. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  90919. this.utilityLayerScene._allowPostProcessClear = false;
  90920. originalScene.getEngine().scenes.pop();
  90921. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  90922. this.utilityLayerScene.detachControl();
  90923. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  90924. if (!_this.processAllEvents) {
  90925. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  90926. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  90927. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  90928. return;
  90929. }
  90930. }
  90931. var pointerEvent = (prePointerInfo.event);
  90932. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  90933. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90934. return;
  90935. }
  90936. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  90937. if (!prePointerInfo.ray && utilityScenePick) {
  90938. prePointerInfo.ray = utilityScenePick.ray;
  90939. }
  90940. // always fire the prepointer oversvable
  90941. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  90942. // allow every non pointer down event to flow to the utility layer
  90943. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  90944. if (!prePointerInfo.skipOnPointerObservable) {
  90945. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90946. }
  90947. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  90948. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90949. }
  90950. return;
  90951. }
  90952. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  90953. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  90954. if (utilityScenePick && utilityScenePick.hit) {
  90955. if (!prePointerInfo.skipOnPointerObservable) {
  90956. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90957. }
  90958. prePointerInfo.skipOnPointerObservable = true;
  90959. }
  90960. }
  90961. else {
  90962. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  90963. var pointerEvent_1 = (prePointerInfo.event);
  90964. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  90965. if (originalScenePick && utilityScenePick) {
  90966. // No pick in utility scene
  90967. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  90968. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90969. // We touched an utility mesh present in the main scene
  90970. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90971. prePointerInfo.skipOnPointerObservable = true;
  90972. }
  90973. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90974. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  90975. }
  90976. }
  90977. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  90978. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  90979. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  90980. // If a previous utility layer set this, do not unset this
  90981. if (!prePointerInfo.skipOnPointerObservable) {
  90982. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  90983. }
  90984. }
  90985. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  90986. // We have a pick in both scenes but main is closer than utility
  90987. // We touched an utility mesh present in the main scene
  90988. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90989. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90990. prePointerInfo.skipOnPointerObservable = true;
  90991. }
  90992. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  90993. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  90994. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  90995. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  90996. }
  90997. }
  90998. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  90999. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  91000. }
  91001. }
  91002. }
  91003. });
  91004. // Render directly on top of existing scene without clearing
  91005. this.utilityLayerScene.autoClear = false;
  91006. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  91007. if (_this.shouldRender) {
  91008. _this.render();
  91009. }
  91010. });
  91011. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  91012. _this.dispose();
  91013. });
  91014. this._updateCamera();
  91015. }
  91016. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  91017. /**
  91018. * 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)
  91019. */
  91020. get: function () {
  91021. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  91022. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91023. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91024. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91025. });
  91026. }
  91027. return UtilityLayerRenderer._DefaultUtilityLayer;
  91028. },
  91029. enumerable: true,
  91030. configurable: true
  91031. });
  91032. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  91033. /**
  91034. * 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)
  91035. */
  91036. get: function () {
  91037. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  91038. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  91039. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  91040. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  91041. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91042. });
  91043. }
  91044. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  91045. },
  91046. enumerable: true,
  91047. configurable: true
  91048. });
  91049. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  91050. if (!prePointerInfo.skipOnPointerObservable) {
  91051. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  91052. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  91053. }
  91054. };
  91055. /**
  91056. * Renders the utility layers scene on top of the original scene
  91057. */
  91058. UtilityLayerRenderer.prototype.render = function () {
  91059. this._updateCamera();
  91060. if (this.utilityLayerScene.activeCamera) {
  91061. // Set the camera's scene to utility layers scene
  91062. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  91063. var camera = this.utilityLayerScene.activeCamera;
  91064. camera._scene = this.utilityLayerScene;
  91065. if (camera.leftCamera) {
  91066. camera.leftCamera._scene = this.utilityLayerScene;
  91067. }
  91068. if (camera.rightCamera) {
  91069. camera.rightCamera._scene = this.utilityLayerScene;
  91070. }
  91071. this.utilityLayerScene.render(false);
  91072. // Reset camera's scene back to original
  91073. camera._scene = oldScene;
  91074. if (camera.leftCamera) {
  91075. camera.leftCamera._scene = oldScene;
  91076. }
  91077. if (camera.rightCamera) {
  91078. camera.rightCamera._scene = oldScene;
  91079. }
  91080. }
  91081. };
  91082. /**
  91083. * Disposes of the renderer
  91084. */
  91085. UtilityLayerRenderer.prototype.dispose = function () {
  91086. this.onPointerOutObservable.clear();
  91087. if (this._afterRenderObserver) {
  91088. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  91089. }
  91090. if (this._sceneDisposeObserver) {
  91091. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91092. }
  91093. if (this._originalPointerObserver) {
  91094. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  91095. }
  91096. this.utilityLayerScene.dispose();
  91097. };
  91098. UtilityLayerRenderer.prototype._updateCamera = function () {
  91099. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  91100. };
  91101. UtilityLayerRenderer._DefaultUtilityLayer = null;
  91102. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  91103. return UtilityLayerRenderer;
  91104. }());
  91105. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  91106. })(BABYLON || (BABYLON = {}));
  91107. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  91108. //# sourceMappingURL=babylon.behavior.js.map
  91109. var BABYLON;
  91110. (function (BABYLON) {
  91111. /**
  91112. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  91113. */
  91114. var PointerDragBehavior = /** @class */ (function () {
  91115. /**
  91116. * Creates a pointer drag behavior that can be attached to a mesh
  91117. * @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)
  91118. */
  91119. function PointerDragBehavior(options) {
  91120. /**
  91121. * 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)
  91122. */
  91123. this.maxDragAngle = 0;
  91124. /**
  91125. * @hidden
  91126. */
  91127. this._useAlternatePickedPointAboveMaxDragAngle = false;
  91128. /**
  91129. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91130. */
  91131. this.currentDraggingPointerID = -1;
  91132. /**
  91133. * If the behavior is currently in a dragging state
  91134. */
  91135. this.dragging = false;
  91136. /**
  91137. * 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)
  91138. */
  91139. this.dragDeltaRatio = 0.2;
  91140. /**
  91141. * If the drag plane orientation should be updated during the dragging (Default: true)
  91142. */
  91143. this.updateDragPlane = true;
  91144. // Debug mode will display drag planes to help visualize behavior
  91145. this._debugMode = false;
  91146. this._moving = false;
  91147. /**
  91148. * Fires each time the attached mesh is dragged with the pointer
  91149. * * delta between last drag position and current drag position in world space
  91150. * * dragDistance along the drag axis
  91151. * * dragPlaneNormal normal of the current drag plane used during the drag
  91152. * * dragPlanePoint in world space where the drag intersects the drag plane
  91153. */
  91154. this.onDragObservable = new BABYLON.Observable();
  91155. /**
  91156. * Fires each time a drag begins (eg. mouse down on mesh)
  91157. */
  91158. this.onDragStartObservable = new BABYLON.Observable();
  91159. /**
  91160. * Fires each time a drag ends (eg. mouse release after drag)
  91161. */
  91162. this.onDragEndObservable = new BABYLON.Observable();
  91163. /**
  91164. * If the attached mesh should be moved when dragged
  91165. */
  91166. this.moveAttached = true;
  91167. /**
  91168. * If the drag behavior will react to drag events (Default: true)
  91169. */
  91170. this.enabled = true;
  91171. /**
  91172. * If camera controls should be detached during the drag
  91173. */
  91174. this.detachCameraControls = true;
  91175. /**
  91176. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  91177. */
  91178. this.useObjectOrienationForDragging = true;
  91179. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  91180. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  91181. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  91182. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91183. this._attachedElement = null;
  91184. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91185. this._lastPointerRay = {};
  91186. this._dragDelta = new BABYLON.Vector3();
  91187. // Variables to avoid instantiation in the below method
  91188. this._pointA = new BABYLON.Vector3(0, 0, 0);
  91189. this._pointB = new BABYLON.Vector3(0, 0, 0);
  91190. this._pointC = new BABYLON.Vector3(0, 0, 0);
  91191. this._lineA = new BABYLON.Vector3(0, 0, 0);
  91192. this._lineB = new BABYLON.Vector3(0, 0, 0);
  91193. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  91194. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  91195. this._options = options ? options : {};
  91196. var optionCount = 0;
  91197. if (this._options.dragAxis) {
  91198. optionCount++;
  91199. }
  91200. if (this._options.dragPlaneNormal) {
  91201. optionCount++;
  91202. }
  91203. if (optionCount > 1) {
  91204. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  91205. }
  91206. }
  91207. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  91208. /**
  91209. * The name of the behavior
  91210. */
  91211. get: function () {
  91212. return "PointerDrag";
  91213. },
  91214. enumerable: true,
  91215. configurable: true
  91216. });
  91217. /**
  91218. * Initializes the behavior
  91219. */
  91220. PointerDragBehavior.prototype.init = function () { };
  91221. /**
  91222. * Attaches the drag behavior the passed in mesh
  91223. * @param ownerNode The mesh that will be dragged around once attached
  91224. */
  91225. PointerDragBehavior.prototype.attach = function (ownerNode) {
  91226. var _this = this;
  91227. this._scene = ownerNode.getScene();
  91228. this._attachedNode = ownerNode;
  91229. // Initialize drag plane to not interfere with existing scene
  91230. if (!PointerDragBehavior._planeScene) {
  91231. if (this._debugMode) {
  91232. PointerDragBehavior._planeScene = this._scene;
  91233. }
  91234. else {
  91235. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  91236. PointerDragBehavior._planeScene.detachControl();
  91237. this._scene.getEngine().scenes.pop();
  91238. this._scene.onDisposeObservable.addOnce(function () {
  91239. PointerDragBehavior._planeScene.dispose();
  91240. PointerDragBehavior._planeScene = null;
  91241. });
  91242. }
  91243. }
  91244. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  91245. // State of the drag
  91246. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  91247. var pickPredicate = function (m) {
  91248. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  91249. };
  91250. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91251. if (!_this.enabled) {
  91252. return;
  91253. }
  91254. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91255. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91256. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  91257. }
  91258. }
  91259. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91260. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91261. _this.releaseDrag();
  91262. }
  91263. }
  91264. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91265. var pointerId = pointerInfo.event.pointerId;
  91266. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  91267. if (!_this._lastPointerRay[pointerId]) {
  91268. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  91269. }
  91270. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  91271. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  91272. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  91273. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  91274. _this._moveDrag(pointerInfo.pickInfo.ray);
  91275. }
  91276. }
  91277. }
  91278. });
  91279. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91280. if (_this._moving && _this.moveAttached) {
  91281. // Slowly move mesh to avoid jitter
  91282. _this._targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  91283. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  91284. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  91285. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  91286. }
  91287. });
  91288. };
  91289. PointerDragBehavior.prototype.releaseDrag = function () {
  91290. this.dragging = false;
  91291. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  91292. this.currentDraggingPointerID = -1;
  91293. this._moving = false;
  91294. // Reattach camera controls
  91295. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91296. this._scene.activeCamera.attachControl(this._attachedElement, true);
  91297. }
  91298. };
  91299. /**
  91300. * Simulates the start of a pointer drag event on the behavior
  91301. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  91302. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  91303. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  91304. */
  91305. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  91306. if (pointerId === void 0) { pointerId = 1; }
  91307. this._startDrag(pointerId, fromRay, startPickedPoint);
  91308. if (this._lastPointerRay[pointerId]) {
  91309. // if there was a last pointer ray drag the object there
  91310. this._moveDrag(this._lastPointerRay[pointerId]);
  91311. }
  91312. };
  91313. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  91314. if (pointerId === void 0) { pointerId = 1; }
  91315. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  91316. return;
  91317. }
  91318. // Create start ray from the camera to the object
  91319. if (fromRay) {
  91320. this._startDragRay.direction.copyFrom(fromRay.direction);
  91321. this._startDragRay.origin.copyFrom(fromRay.origin);
  91322. }
  91323. else {
  91324. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  91325. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  91326. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  91327. }
  91328. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  91329. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  91330. if (pickedPoint) {
  91331. this.dragging = true;
  91332. this.currentDraggingPointerID = 1;
  91333. this.lastDragPosition.copyFrom(pickedPoint);
  91334. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  91335. this._targetPosition.copyFrom(this._attachedNode.absolutePosition);
  91336. // Detatch camera controls
  91337. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  91338. if (this._scene.activeCamera.inputs.attachedElement) {
  91339. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  91340. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  91341. }
  91342. else {
  91343. this._attachedElement = null;
  91344. }
  91345. }
  91346. }
  91347. };
  91348. PointerDragBehavior.prototype._moveDrag = function (ray) {
  91349. this._moving = true;
  91350. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  91351. if (pickedPoint) {
  91352. if (this.updateDragPlane) {
  91353. this._updateDragPlanePosition(ray, pickedPoint);
  91354. }
  91355. var dragLength = 0;
  91356. // depending on the drag mode option drag accordingly
  91357. if (this._options.dragAxis) {
  91358. // Convert local drag axis to world
  91359. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  91360. // Project delta drag from the drag plane onto the drag axis
  91361. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  91362. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  91363. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  91364. }
  91365. else {
  91366. dragLength = this._dragDelta.length();
  91367. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  91368. }
  91369. this._targetPosition.addInPlace(this._dragDelta);
  91370. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  91371. this.lastDragPosition.copyFrom(pickedPoint);
  91372. }
  91373. };
  91374. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  91375. var _this = this;
  91376. if (!ray) {
  91377. return null;
  91378. }
  91379. // Calculate angle between plane normal and ray
  91380. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  91381. // Correct if ray is casted from oposite side
  91382. if (angle > Math.PI / 2) {
  91383. angle = Math.PI - angle;
  91384. }
  91385. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  91386. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  91387. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  91388. // Invert ray direction along the towards object axis
  91389. this._tmpVector.copyFrom(ray.direction);
  91390. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  91391. this._alternatePickedPoint.normalize();
  91392. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  91393. this._tmpVector.addInPlace(this._alternatePickedPoint);
  91394. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  91395. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  91396. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  91397. this._alternatePickedPoint.addInPlace(this._tmpVector);
  91398. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  91399. return this._alternatePickedPoint;
  91400. }
  91401. else {
  91402. return null;
  91403. }
  91404. }
  91405. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  91406. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  91407. return pickResult.pickedPoint;
  91408. }
  91409. else {
  91410. return null;
  91411. }
  91412. };
  91413. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  91414. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  91415. this._pointA.copyFrom(dragPlanePosition);
  91416. if (this._options.dragAxis) {
  91417. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  91418. // Calculate plane normal in direction of camera but perpendicular to drag axis
  91419. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  91420. ray.origin.subtractToRef(this._pointA, this._pointC);
  91421. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  91422. // Get perpendicular line from direction to camera and drag axis
  91423. this._pointB.subtractToRef(this._pointA, this._lineA);
  91424. this._pointC.subtractToRef(this._pointA, this._lineB);
  91425. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  91426. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  91427. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  91428. this._lookAt.normalize();
  91429. this._dragPlane.position.copyFrom(this._pointA);
  91430. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  91431. this._dragPlane.lookAt(this._lookAt);
  91432. }
  91433. else if (this._options.dragPlaneNormal) {
  91434. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  91435. this._dragPlane.position.copyFrom(this._pointA);
  91436. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  91437. this._dragPlane.lookAt(this._lookAt);
  91438. }
  91439. else {
  91440. this._dragPlane.position.copyFrom(this._pointA);
  91441. this._dragPlane.lookAt(ray.origin);
  91442. }
  91443. this._dragPlane.computeWorldMatrix(true);
  91444. };
  91445. /**
  91446. * Detaches the behavior from the mesh
  91447. */
  91448. PointerDragBehavior.prototype.detach = function () {
  91449. if (this._pointerObserver) {
  91450. this._scene.onPointerObservable.remove(this._pointerObserver);
  91451. }
  91452. if (this._beforeRenderObserver) {
  91453. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91454. }
  91455. };
  91456. return PointerDragBehavior;
  91457. }());
  91458. BABYLON.PointerDragBehavior = PointerDragBehavior;
  91459. })(BABYLON || (BABYLON = {}));
  91460. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  91461. var BABYLON;
  91462. (function (BABYLON) {
  91463. /**
  91464. * A behavior that when attached to a mesh will allow the mesh to be scaled
  91465. */
  91466. var MultiPointerScaleBehavior = /** @class */ (function () {
  91467. function MultiPointerScaleBehavior() {
  91468. this._startDistance = 0;
  91469. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  91470. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  91471. this._sceneRenderObserver = null;
  91472. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  91473. this._dragBehaviorA.moveAttached = false;
  91474. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  91475. this._dragBehaviorB.moveAttached = false;
  91476. }
  91477. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  91478. /**
  91479. * The name of the behavior
  91480. */
  91481. get: function () {
  91482. return "MultiPointerScale";
  91483. },
  91484. enumerable: true,
  91485. configurable: true
  91486. });
  91487. /**
  91488. * Initializes the behavior
  91489. */
  91490. MultiPointerScaleBehavior.prototype.init = function () { };
  91491. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  91492. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  91493. };
  91494. /**
  91495. * Attaches the scale behavior the passed in mesh
  91496. * @param ownerNode The mesh that will be scaled around once attached
  91497. */
  91498. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  91499. var _this = this;
  91500. this._ownerNode = ownerNode;
  91501. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  91502. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  91503. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91504. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91505. _this._dragBehaviorA.releaseDrag();
  91506. }
  91507. else {
  91508. _this._initialScale.copyFrom(ownerNode.scaling);
  91509. _this._startDistance = _this._getCurrentDistance();
  91510. }
  91511. }
  91512. });
  91513. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  91514. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91515. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  91516. _this._dragBehaviorB.releaseDrag();
  91517. }
  91518. else {
  91519. _this._initialScale.copyFrom(ownerNode.scaling);
  91520. _this._startDistance = _this._getCurrentDistance();
  91521. }
  91522. }
  91523. });
  91524. // Once both drag behaviors are active scale based on the distance between the two pointers
  91525. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91526. behavior.onDragObservable.add(function () {
  91527. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91528. var ratio = _this._getCurrentDistance() / _this._startDistance;
  91529. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  91530. }
  91531. });
  91532. });
  91533. ownerNode.addBehavior(this._dragBehaviorA);
  91534. ownerNode.addBehavior(this._dragBehaviorB);
  91535. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91536. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91537. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  91538. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  91539. if (change.length() > 0.01) {
  91540. ownerNode.scaling.addInPlace(change);
  91541. }
  91542. }
  91543. });
  91544. };
  91545. /**
  91546. * Detaches the behavior from the mesh
  91547. */
  91548. MultiPointerScaleBehavior.prototype.detach = function () {
  91549. var _this = this;
  91550. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91551. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  91552. behavior.onDragStartObservable.clear();
  91553. behavior.onDragObservable.clear();
  91554. _this._ownerNode.removeBehavior(behavior);
  91555. });
  91556. };
  91557. return MultiPointerScaleBehavior;
  91558. }());
  91559. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  91560. })(BABYLON || (BABYLON = {}));
  91561. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  91562. var BABYLON;
  91563. (function (BABYLON) {
  91564. /**
  91565. * 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
  91566. */
  91567. var SixDofDragBehavior = /** @class */ (function () {
  91568. function SixDofDragBehavior() {
  91569. this._sceneRenderObserver = null;
  91570. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  91571. this._moving = false;
  91572. this._startingOrientation = new BABYLON.Quaternion();
  91573. /**
  91574. * 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)
  91575. */
  91576. this.zDragFactor = 3;
  91577. /**
  91578. * If the behavior is currently in a dragging state
  91579. */
  91580. this.dragging = false;
  91581. /**
  91582. * 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)
  91583. */
  91584. this.dragDeltaRatio = 0.2;
  91585. /**
  91586. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  91587. */
  91588. this.currentDraggingPointerID = -1;
  91589. /**
  91590. * If camera controls should be detached during the drag
  91591. */
  91592. this.detachCameraControls = true;
  91593. }
  91594. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  91595. /**
  91596. * The name of the behavior
  91597. */
  91598. get: function () {
  91599. return "SixDofDrag";
  91600. },
  91601. enumerable: true,
  91602. configurable: true
  91603. });
  91604. /**
  91605. * Initializes the behavior
  91606. */
  91607. SixDofDragBehavior.prototype.init = function () { };
  91608. /**
  91609. * Attaches the scale behavior the passed in mesh
  91610. * @param ownerNode The mesh that will be scaled around once attached
  91611. */
  91612. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  91613. var _this = this;
  91614. this._ownerNode = ownerNode;
  91615. this._scene = this._ownerNode.getScene();
  91616. if (!SixDofDragBehavior._virtualScene) {
  91617. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  91618. this._scene.getEngine().scenes.pop();
  91619. }
  91620. var pickedMesh = null;
  91621. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  91622. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  91623. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91624. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  91625. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91626. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  91627. var pickPredicate = function (m) {
  91628. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  91629. };
  91630. var attachedElement = null;
  91631. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91632. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91633. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91634. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91635. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91636. }
  91637. pickedMesh = _this._ownerNode;
  91638. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91639. // Set position and orientation of the controller
  91640. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91641. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91642. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  91643. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91644. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  91645. if (!pickedMesh.rotationQuaternion) {
  91646. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  91647. }
  91648. var oldParent = pickedMesh.parent;
  91649. pickedMesh.setParent(null);
  91650. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  91651. pickedMesh.setParent(oldParent);
  91652. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91653. // Update state
  91654. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91655. _this.dragging = true;
  91656. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  91657. // Detatch camera controls
  91658. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91659. if (_this._scene.activeCamera.inputs.attachedElement) {
  91660. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  91661. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  91662. }
  91663. else {
  91664. attachedElement = null;
  91665. }
  91666. }
  91667. }
  91668. }
  91669. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91670. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91671. _this.dragging = false;
  91672. _this._moving = false;
  91673. _this.currentDraggingPointerID = -1;
  91674. pickedMesh = null;
  91675. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91676. // Reattach camera controls
  91677. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91678. _this._scene.activeCamera.attachControl(attachedElement, true);
  91679. }
  91680. }
  91681. }
  91682. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91683. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  91684. var zDragFactor = _this.zDragFactor;
  91685. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91686. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91687. zDragFactor = 0;
  91688. }
  91689. // Calculate controller drag distance in controller space
  91690. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  91691. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91692. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  91693. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91694. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  91695. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  91696. if (_this._virtualDragMesh.position.z < 0) {
  91697. _this._virtualDragMesh.position.z = 0;
  91698. }
  91699. // Update the controller position
  91700. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91701. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91702. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91703. // Move the virtualObjectsPosition into the picked mesh's space if needed
  91704. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91705. if (pickedMesh.parent) {
  91706. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  91707. }
  91708. if (!_this._moving) {
  91709. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  91710. }
  91711. _this._moving = true;
  91712. }
  91713. }
  91714. });
  91715. var tmpQuaternion = new BABYLON.Quaternion();
  91716. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91717. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91718. if (_this.dragging && _this._moving && pickedMesh) {
  91719. // Slowly move mesh to avoid jitter
  91720. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  91721. // Get change in rotation
  91722. tmpQuaternion.copyFrom(_this._startingOrientation);
  91723. tmpQuaternion.x = -tmpQuaternion.x;
  91724. tmpQuaternion.y = -tmpQuaternion.y;
  91725. tmpQuaternion.z = -tmpQuaternion.z;
  91726. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  91727. // Convert change in rotation to only y axis rotation
  91728. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  91729. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  91730. // Slowly move mesh to avoid jitter
  91731. var oldParent = pickedMesh.parent;
  91732. pickedMesh.setParent(null);
  91733. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  91734. pickedMesh.setParent(oldParent);
  91735. }
  91736. });
  91737. };
  91738. /**
  91739. * Detaches the behavior from the mesh
  91740. */
  91741. SixDofDragBehavior.prototype.detach = function () {
  91742. if (this._scene) {
  91743. this._scene.onPointerObservable.remove(this._pointerObserver);
  91744. }
  91745. if (this._ownerNode) {
  91746. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91747. }
  91748. if (this._virtualOriginMesh) {
  91749. this._virtualOriginMesh.dispose();
  91750. }
  91751. if (this._virtualDragMesh) {
  91752. this._virtualDragMesh.dispose();
  91753. }
  91754. };
  91755. return SixDofDragBehavior;
  91756. }());
  91757. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  91758. })(BABYLON || (BABYLON = {}));
  91759. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  91760. var BABYLON;
  91761. (function (BABYLON) {
  91762. /**
  91763. * @hidden
  91764. */
  91765. var FaceDirectionInfo = /** @class */ (function () {
  91766. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  91767. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  91768. if (diff === void 0) { diff = 0; }
  91769. if (ignore === void 0) { ignore = false; }
  91770. this.direction = direction;
  91771. this.rotatedDirection = rotatedDirection;
  91772. this.diff = diff;
  91773. this.ignore = ignore;
  91774. }
  91775. return FaceDirectionInfo;
  91776. }());
  91777. /**
  91778. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  91779. */
  91780. var AttachToBoxBehavior = /** @class */ (function () {
  91781. /**
  91782. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  91783. * @param ui The transform node that should be attched to the mesh
  91784. */
  91785. function AttachToBoxBehavior(ui) {
  91786. this.ui = ui;
  91787. /**
  91788. * The name of the behavior
  91789. */
  91790. this.name = "AttachToBoxBehavior";
  91791. /**
  91792. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  91793. */
  91794. this.distanceAwayFromFace = 0.15;
  91795. /**
  91796. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  91797. */
  91798. this.distanceAwayFromBottomOfFace = 0.15;
  91799. 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))];
  91800. this._tmpMatrix = new BABYLON.Matrix();
  91801. this._tmpVector = new BABYLON.Vector3();
  91802. this._zeroVector = BABYLON.Vector3.Zero();
  91803. this._lookAtTmpMatrix = new BABYLON.Matrix();
  91804. /* Does nothing */
  91805. }
  91806. /**
  91807. * Initializes the behavior
  91808. */
  91809. AttachToBoxBehavior.prototype.init = function () {
  91810. /* Does nothing */
  91811. };
  91812. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  91813. var _this = this;
  91814. // Go over each face and calculate the angle between the face's normal and targetDirection
  91815. this._faceVectors.forEach(function (v) {
  91816. if (!_this._target.rotationQuaternion) {
  91817. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  91818. }
  91819. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  91820. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  91821. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  91822. });
  91823. // Return the face information of the one with the normal closeset to target direction
  91824. return this._faceVectors.reduce(function (min, p) {
  91825. if (min.ignore) {
  91826. return p;
  91827. }
  91828. else if (p.ignore) {
  91829. return min;
  91830. }
  91831. else {
  91832. return min.diff < p.diff ? min : p;
  91833. }
  91834. }, this._faceVectors[0]);
  91835. };
  91836. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  91837. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  91838. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  91839. this._lookAtTmpMatrix.invert();
  91840. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  91841. };
  91842. /**
  91843. * Attaches the AttachToBoxBehavior to the passed in mesh
  91844. * @param target The mesh that the specified node will be attached to
  91845. */
  91846. AttachToBoxBehavior.prototype.attach = function (target) {
  91847. var _this = this;
  91848. this._target = target;
  91849. this._scene = this._target.getScene();
  91850. // Every frame, update the app bars position
  91851. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91852. if (!_this._scene.activeCamera) {
  91853. return;
  91854. }
  91855. // Find the face closest to the cameras position
  91856. var cameraPos = _this._scene.activeCamera.position;
  91857. if (_this._scene.activeCamera.devicePosition) {
  91858. cameraPos = _this._scene.activeCamera.devicePosition;
  91859. }
  91860. var facing = _this._closestFace(cameraPos.subtract(target.position));
  91861. if (_this._scene.activeCamera.leftCamera) {
  91862. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91863. }
  91864. else {
  91865. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91866. }
  91867. // Get camera up direction
  91868. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  91869. // Ignore faces to not select a parrelel face for the up vector of the UI
  91870. _this._faceVectors.forEach(function (v) {
  91871. if (facing.direction.x && v.direction.x) {
  91872. v.ignore = true;
  91873. }
  91874. if (facing.direction.y && v.direction.y) {
  91875. v.ignore = true;
  91876. }
  91877. if (facing.direction.z && v.direction.z) {
  91878. v.ignore = true;
  91879. }
  91880. });
  91881. var facingUp = _this._closestFace(_this._tmpVector);
  91882. // Unignore faces
  91883. _this._faceVectors.forEach(function (v) {
  91884. v.ignore = false;
  91885. });
  91886. // Position the app bar on that face
  91887. _this.ui.position.copyFrom(target.position);
  91888. if (facing.direction.x) {
  91889. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91890. _this.ui.position.addInPlace(_this._tmpVector);
  91891. }
  91892. if (facing.direction.y) {
  91893. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91894. _this.ui.position.addInPlace(_this._tmpVector);
  91895. }
  91896. if (facing.direction.z) {
  91897. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91898. _this.ui.position.addInPlace(_this._tmpVector);
  91899. }
  91900. // Rotate to be oriented properly to the camera
  91901. if (!_this.ui.rotationQuaternion) {
  91902. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  91903. }
  91904. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  91905. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  91906. // Place ui the correct distance from the bottom of the mesh
  91907. if (facingUp.direction.x) {
  91908. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  91909. }
  91910. if (facingUp.direction.y) {
  91911. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  91912. }
  91913. if (facingUp.direction.z) {
  91914. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  91915. }
  91916. _this.ui.position.addInPlace(_this._tmpVector);
  91917. });
  91918. };
  91919. /**
  91920. * Detaches the behavior from the mesh
  91921. */
  91922. AttachToBoxBehavior.prototype.detach = function () {
  91923. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  91924. };
  91925. return AttachToBoxBehavior;
  91926. }());
  91927. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  91928. })(BABYLON || (BABYLON = {}));
  91929. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  91930. var BABYLON;
  91931. (function (BABYLON) {
  91932. /**
  91933. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  91934. */
  91935. var FadeInOutBehavior = /** @class */ (function () {
  91936. /**
  91937. * Instatiates the FadeInOutBehavior
  91938. */
  91939. function FadeInOutBehavior() {
  91940. var _this = this;
  91941. /**
  91942. * Time in milliseconds to delay before fading in (Default: 0)
  91943. */
  91944. this.delay = 0;
  91945. /**
  91946. * Time in milliseconds for the mesh to fade in (Default: 300)
  91947. */
  91948. this.fadeInTime = 300;
  91949. this._millisecondsPerFrame = 1000 / 60;
  91950. this._hovered = false;
  91951. this._hoverValue = 0;
  91952. this._ownerNode = null;
  91953. this._update = function () {
  91954. if (_this._ownerNode) {
  91955. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  91956. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  91957. if (_this._ownerNode.visibility > 1) {
  91958. _this._setAllVisibility(_this._ownerNode, 1);
  91959. _this._hoverValue = _this.fadeInTime + _this.delay;
  91960. return;
  91961. }
  91962. else if (_this._ownerNode.visibility < 0) {
  91963. _this._setAllVisibility(_this._ownerNode, 0);
  91964. if (_this._hoverValue < 0) {
  91965. _this._hoverValue = 0;
  91966. return;
  91967. }
  91968. }
  91969. setTimeout(_this._update, _this._millisecondsPerFrame);
  91970. }
  91971. };
  91972. }
  91973. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  91974. /**
  91975. * The name of the behavior
  91976. */
  91977. get: function () {
  91978. return "FadeInOut";
  91979. },
  91980. enumerable: true,
  91981. configurable: true
  91982. });
  91983. /**
  91984. * Initializes the behavior
  91985. */
  91986. FadeInOutBehavior.prototype.init = function () {
  91987. };
  91988. /**
  91989. * Attaches the fade behavior on the passed in mesh
  91990. * @param ownerNode The mesh that will be faded in/out once attached
  91991. */
  91992. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  91993. this._ownerNode = ownerNode;
  91994. this._setAllVisibility(this._ownerNode, 0);
  91995. };
  91996. /**
  91997. * Detaches the behavior from the mesh
  91998. */
  91999. FadeInOutBehavior.prototype.detach = function () {
  92000. this._ownerNode = null;
  92001. };
  92002. /**
  92003. * Triggers the mesh to begin fading in or out
  92004. * @param value if the object should fade in or out (true to fade in)
  92005. */
  92006. FadeInOutBehavior.prototype.fadeIn = function (value) {
  92007. this._hovered = value;
  92008. this._update();
  92009. };
  92010. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  92011. var _this = this;
  92012. mesh.visibility = value;
  92013. mesh.getChildMeshes().forEach(function (c) {
  92014. _this._setAllVisibility(c, value);
  92015. });
  92016. };
  92017. return FadeInOutBehavior;
  92018. }());
  92019. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  92020. })(BABYLON || (BABYLON = {}));
  92021. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  92022. var BABYLON;
  92023. (function (BABYLON) {
  92024. /**
  92025. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  92026. */
  92027. var Gizmo = /** @class */ (function () {
  92028. /**
  92029. * Creates a gizmo
  92030. * @param gizmoLayer The utility layer the gizmo will be added to
  92031. */
  92032. function Gizmo(
  92033. /** The utility layer the gizmo will be added to */
  92034. gizmoLayer) {
  92035. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92036. var _this = this;
  92037. this.gizmoLayer = gizmoLayer;
  92038. /**
  92039. * Ratio for the scale of the gizmo (Default: 1)
  92040. */
  92041. this.scaleRatio = 1;
  92042. this._tmpMatrix = new BABYLON.Matrix();
  92043. /**
  92044. * If a custom mesh has been set (Default: false)
  92045. */
  92046. this._customMeshSet = false;
  92047. /**
  92048. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  92049. */
  92050. this.updateGizmoRotationToMatchAttachedMesh = true;
  92051. /**
  92052. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  92053. */
  92054. this.updateGizmoPositionToMatchAttachedMesh = true;
  92055. /**
  92056. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  92057. */
  92058. this._updateScale = true;
  92059. this._interactionsEnabled = true;
  92060. this._tempVector = new BABYLON.Vector3();
  92061. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  92062. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  92063. _this._update();
  92064. });
  92065. this.attachedMesh = null;
  92066. }
  92067. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  92068. /**
  92069. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  92070. * * When set, interactions will be enabled
  92071. */
  92072. get: function () {
  92073. return this._attachedMesh;
  92074. },
  92075. set: function (value) {
  92076. this._attachedMesh = value;
  92077. this._rootMesh.setEnabled(value ? true : false);
  92078. this._attachedMeshChanged(value);
  92079. },
  92080. enumerable: true,
  92081. configurable: true
  92082. });
  92083. /**
  92084. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92085. * @param mesh The mesh to replace the default mesh of the gizmo
  92086. */
  92087. Gizmo.prototype.setCustomMesh = function (mesh) {
  92088. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  92089. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  92090. }
  92091. this._rootMesh.getChildMeshes().forEach(function (c) {
  92092. c.dispose();
  92093. });
  92094. mesh.parent = this._rootMesh;
  92095. this._customMeshSet = true;
  92096. };
  92097. Gizmo.prototype._attachedMeshChanged = function (value) {
  92098. };
  92099. /**
  92100. * @hidden
  92101. * Updates the gizmo to match the attached mesh's position/rotation
  92102. */
  92103. Gizmo.prototype._update = function () {
  92104. if (this.attachedMesh) {
  92105. if (this.updateGizmoRotationToMatchAttachedMesh) {
  92106. if (!this._rootMesh.rotationQuaternion) {
  92107. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  92108. }
  92109. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  92110. this._tempVector.copyFrom(this.attachedMesh.scaling);
  92111. if (this.attachedMesh.scaling.x < 0) {
  92112. this.attachedMesh.scaling.x *= -1;
  92113. }
  92114. if (this.attachedMesh.scaling.y < 0) {
  92115. this.attachedMesh.scaling.y *= -1;
  92116. }
  92117. if (this.attachedMesh.scaling.z < 0) {
  92118. this.attachedMesh.scaling.z *= -1;
  92119. }
  92120. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  92121. this.attachedMesh.scaling.copyFrom(this._tempVector);
  92122. this.attachedMesh.computeWorldMatrix();
  92123. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  92124. }
  92125. else if (this._rootMesh.rotationQuaternion) {
  92126. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  92127. }
  92128. if (this.updateGizmoPositionToMatchAttachedMesh) {
  92129. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  92130. }
  92131. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  92132. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  92133. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  92134. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  92135. }
  92136. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  92137. var dist = this._tempVector.length() * this.scaleRatio;
  92138. this._rootMesh.scaling.set(dist, dist, dist);
  92139. }
  92140. }
  92141. };
  92142. /**
  92143. * Disposes of the gizmo
  92144. */
  92145. Gizmo.prototype.dispose = function () {
  92146. this._rootMesh.dispose();
  92147. if (this._beforeRenderObserver) {
  92148. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92149. }
  92150. };
  92151. return Gizmo;
  92152. }());
  92153. BABYLON.Gizmo = Gizmo;
  92154. })(BABYLON || (BABYLON = {}));
  92155. //# sourceMappingURL=babylon.gizmo.js.map
  92156. var BABYLON;
  92157. (function (BABYLON) {
  92158. /**
  92159. * Single axis drag gizmo
  92160. */
  92161. var AxisDragGizmo = /** @class */ (function (_super) {
  92162. __extends(AxisDragGizmo, _super);
  92163. /**
  92164. * Creates an AxisDragGizmo
  92165. * @param gizmoLayer The utility layer the gizmo will be added to
  92166. * @param dragAxis The axis which the gizmo will be able to drag on
  92167. * @param color The color of the gizmo
  92168. */
  92169. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  92170. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92171. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92172. var _this = _super.call(this, gizmoLayer) || this;
  92173. _this._pointerObserver = null;
  92174. /**
  92175. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92176. */
  92177. _this.snapDistance = 0;
  92178. /**
  92179. * Event that fires each time the gizmo snaps to a new location.
  92180. * * snapDistance is the the change in distance
  92181. */
  92182. _this.onSnapObservable = new BABYLON.Observable();
  92183. // Create Material
  92184. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92185. coloredMaterial.disableLighting = true;
  92186. coloredMaterial.emissiveColor = color;
  92187. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92188. hoverMaterial.disableLighting = true;
  92189. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92190. // Build mesh on root node
  92191. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92192. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  92193. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92194. arrowTail.color = coloredMaterial.emissiveColor;
  92195. arrow.addChild(arrowMesh);
  92196. arrow.addChild(arrowTail);
  92197. // Position arrow pointing in its drag axis
  92198. arrowMesh.scaling.scaleInPlace(0.05);
  92199. arrowMesh.material = coloredMaterial;
  92200. arrowMesh.rotation.x = Math.PI / 2;
  92201. arrowMesh.position.z += 0.3;
  92202. arrowTail.scaling.scaleInPlace(0.26);
  92203. arrowTail.rotation.x = Math.PI / 2;
  92204. arrowTail.material = coloredMaterial;
  92205. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92206. arrow.scaling.scaleInPlace(1 / 3);
  92207. _this._rootMesh.addChild(arrow);
  92208. var currentSnapDragDistance = 0;
  92209. var tmpVector = new BABYLON.Vector3();
  92210. var tmpSnapEvent = { snapDistance: 0 };
  92211. // Add drag behavior to handle events when the gizmo is dragged
  92212. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92213. _this.dragBehavior.moveAttached = false;
  92214. _this._rootMesh.addBehavior(_this.dragBehavior);
  92215. var localDelta = new BABYLON.Vector3();
  92216. var tmpMatrix = new BABYLON.Matrix();
  92217. _this.dragBehavior.onDragObservable.add(function (event) {
  92218. if (_this.attachedMesh) {
  92219. // Convert delta to local translation if it has a parent
  92220. if (_this.attachedMesh.parent) {
  92221. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92222. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  92223. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  92224. }
  92225. else {
  92226. localDelta.copyFrom(event.delta);
  92227. }
  92228. // Snapping logic
  92229. if (_this.snapDistance == 0) {
  92230. _this.attachedMesh.position.addInPlace(localDelta);
  92231. }
  92232. else {
  92233. currentSnapDragDistance += event.dragDistance;
  92234. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92235. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  92236. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92237. localDelta.normalizeToRef(tmpVector);
  92238. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  92239. _this.attachedMesh.position.addInPlace(tmpVector);
  92240. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92241. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92242. }
  92243. }
  92244. }
  92245. });
  92246. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92247. if (_this._customMeshSet) {
  92248. return;
  92249. }
  92250. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92251. var material = isHovered ? hoverMaterial : coloredMaterial;
  92252. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92253. m.material = material;
  92254. if (m.color) {
  92255. m.color = material.emissiveColor;
  92256. }
  92257. });
  92258. });
  92259. return _this;
  92260. }
  92261. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  92262. if (this.dragBehavior) {
  92263. this.dragBehavior.enabled = value ? true : false;
  92264. }
  92265. };
  92266. /**
  92267. * Disposes of the gizmo
  92268. */
  92269. AxisDragGizmo.prototype.dispose = function () {
  92270. this.onSnapObservable.clear();
  92271. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92272. this.dragBehavior.detach();
  92273. _super.prototype.dispose.call(this);
  92274. };
  92275. return AxisDragGizmo;
  92276. }(BABYLON.Gizmo));
  92277. BABYLON.AxisDragGizmo = AxisDragGizmo;
  92278. })(BABYLON || (BABYLON = {}));
  92279. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  92280. var BABYLON;
  92281. (function (BABYLON) {
  92282. /**
  92283. * Single axis scale gizmo
  92284. */
  92285. var AxisScaleGizmo = /** @class */ (function (_super) {
  92286. __extends(AxisScaleGizmo, _super);
  92287. /**
  92288. * Creates an AxisScaleGizmo
  92289. * @param gizmoLayer The utility layer the gizmo will be added to
  92290. * @param dragAxis The axis which the gizmo will be able to scale on
  92291. * @param color The color of the gizmo
  92292. */
  92293. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  92294. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92295. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92296. var _this = _super.call(this, gizmoLayer) || this;
  92297. _this._pointerObserver = null;
  92298. /**
  92299. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92300. */
  92301. _this.snapDistance = 0;
  92302. /**
  92303. * Event that fires each time the gizmo snaps to a new location.
  92304. * * snapDistance is the the change in distance
  92305. */
  92306. _this.onSnapObservable = new BABYLON.Observable();
  92307. /**
  92308. * If the scaling operation should be done on all axis (default: false)
  92309. */
  92310. _this.uniformScaling = false;
  92311. // Create Material
  92312. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92313. _this._coloredMaterial.disableLighting = true;
  92314. _this._coloredMaterial.emissiveColor = color;
  92315. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92316. hoverMaterial.disableLighting = true;
  92317. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92318. // Build mesh on root node
  92319. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92320. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  92321. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  92322. arrowTail.color = _this._coloredMaterial.emissiveColor;
  92323. arrow.addChild(arrowMesh);
  92324. arrow.addChild(arrowTail);
  92325. // Position arrow pointing in its drag axis
  92326. arrowMesh.scaling.scaleInPlace(0.1);
  92327. arrowMesh.material = _this._coloredMaterial;
  92328. arrowMesh.rotation.x = Math.PI / 2;
  92329. arrowMesh.position.z += 0.3;
  92330. arrowTail.scaling.scaleInPlace(0.26);
  92331. arrowTail.rotation.x = Math.PI / 2;
  92332. arrowTail.material = _this._coloredMaterial;
  92333. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  92334. _this._rootMesh.addChild(arrow);
  92335. arrow.scaling.scaleInPlace(1 / 3);
  92336. // Add drag behavior to handle events when the gizmo is dragged
  92337. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92338. _this.dragBehavior.moveAttached = false;
  92339. _this._rootMesh.addBehavior(_this.dragBehavior);
  92340. var currentSnapDragDistance = 0;
  92341. var tmpVector = new BABYLON.Vector3();
  92342. var tmpSnapEvent = { snapDistance: 0 };
  92343. _this.dragBehavior.onDragObservable.add(function (event) {
  92344. if (_this.attachedMesh) {
  92345. // Snapping logic
  92346. var snapped = false;
  92347. var dragSteps = 0;
  92348. if (_this.uniformScaling) {
  92349. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  92350. if (tmpVector.y < 0) {
  92351. tmpVector.scaleInPlace(-1);
  92352. }
  92353. }
  92354. else {
  92355. tmpVector.copyFrom(dragAxis);
  92356. }
  92357. if (_this.snapDistance == 0) {
  92358. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  92359. }
  92360. else {
  92361. currentSnapDragDistance += event.dragDistance;
  92362. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92363. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92364. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92365. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  92366. snapped = true;
  92367. }
  92368. else {
  92369. tmpVector.scaleInPlace(0);
  92370. }
  92371. }
  92372. _this.attachedMesh.scaling.addInPlace(tmpVector);
  92373. if (snapped) {
  92374. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  92375. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92376. }
  92377. }
  92378. });
  92379. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92380. if (_this._customMeshSet) {
  92381. return;
  92382. }
  92383. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92384. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  92385. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92386. m.material = material;
  92387. if (m.color) {
  92388. m.color = material.emissiveColor;
  92389. }
  92390. });
  92391. });
  92392. return _this;
  92393. }
  92394. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  92395. if (this.dragBehavior) {
  92396. this.dragBehavior.enabled = value ? true : false;
  92397. }
  92398. };
  92399. /**
  92400. * Disposes of the gizmo
  92401. */
  92402. AxisScaleGizmo.prototype.dispose = function () {
  92403. this.onSnapObservable.clear();
  92404. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92405. this.dragBehavior.detach();
  92406. _super.prototype.dispose.call(this);
  92407. };
  92408. /**
  92409. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  92410. * @param mesh The mesh to replace the default mesh of the gizmo
  92411. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  92412. */
  92413. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  92414. var _this = this;
  92415. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  92416. _super.prototype.setCustomMesh.call(this, mesh);
  92417. if (useGizmoMaterial) {
  92418. this._rootMesh.getChildMeshes().forEach(function (m) {
  92419. m.material = _this._coloredMaterial;
  92420. if (m.color) {
  92421. m.color = _this._coloredMaterial.emissiveColor;
  92422. }
  92423. });
  92424. this._customMeshSet = false;
  92425. }
  92426. };
  92427. return AxisScaleGizmo;
  92428. }(BABYLON.Gizmo));
  92429. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  92430. })(BABYLON || (BABYLON = {}));
  92431. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  92432. var BABYLON;
  92433. (function (BABYLON) {
  92434. /**
  92435. * Single plane rotation gizmo
  92436. */
  92437. var PlaneRotationGizmo = /** @class */ (function (_super) {
  92438. __extends(PlaneRotationGizmo, _super);
  92439. /**
  92440. * Creates a PlaneRotationGizmo
  92441. * @param gizmoLayer The utility layer the gizmo will be added to
  92442. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  92443. * @param color The color of the gizmo
  92444. */
  92445. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  92446. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92447. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92448. var _this = _super.call(this, gizmoLayer) || this;
  92449. _this._pointerObserver = null;
  92450. /**
  92451. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  92452. */
  92453. _this.snapDistance = 0;
  92454. /**
  92455. * Event that fires each time the gizmo snaps to a new location.
  92456. * * snapDistance is the the change in distance
  92457. */
  92458. _this.onSnapObservable = new BABYLON.Observable();
  92459. // Create Material
  92460. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92461. coloredMaterial.disableLighting = true;
  92462. coloredMaterial.emissiveColor = color;
  92463. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92464. hoverMaterial.disableLighting = true;
  92465. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92466. // Build mesh on root node
  92467. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92468. // Create circle out of lines
  92469. var tessellation = 20;
  92470. var radius = 0.8;
  92471. var points = new Array();
  92472. for (var i = 0; i < tessellation; i++) {
  92473. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  92474. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  92475. }
  92476. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  92477. rotationMesh.color = coloredMaterial.emissiveColor;
  92478. // Position arrow pointing in its drag axis
  92479. rotationMesh.scaling.scaleInPlace(0.26);
  92480. rotationMesh.material = coloredMaterial;
  92481. rotationMesh.rotation.x = Math.PI / 2;
  92482. parentMesh.addChild(rotationMesh);
  92483. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  92484. _this._rootMesh.addChild(parentMesh);
  92485. parentMesh.scaling.scaleInPlace(1 / 3);
  92486. // Add drag behavior to handle events when the gizmo is dragged
  92487. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  92488. _this.dragBehavior.moveAttached = false;
  92489. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  92490. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  92491. _this._rootMesh.addBehavior(_this.dragBehavior);
  92492. var lastDragPosition = new BABYLON.Vector3();
  92493. _this.dragBehavior.onDragStartObservable.add(function (e) {
  92494. if (_this.attachedMesh) {
  92495. lastDragPosition.copyFrom(e.dragPlanePoint);
  92496. }
  92497. });
  92498. var rotationMatrix = new BABYLON.Matrix();
  92499. var planeNormalTowardsCamera = new BABYLON.Vector3();
  92500. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  92501. var tmpSnapEvent = { snapDistance: 0 };
  92502. var currentSnapDragDistance = 0;
  92503. var tmpMatrix = new BABYLON.Matrix();
  92504. var tmpVector = new BABYLON.Vector3();
  92505. var amountToRotate = new BABYLON.Quaternion();
  92506. _this.dragBehavior.onDragObservable.add(function (event) {
  92507. if (_this.attachedMesh) {
  92508. if (!_this.attachedMesh.rotationQuaternion) {
  92509. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92510. }
  92511. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  92512. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  92513. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  92514. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  92515. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  92516. var angle = Math.atan2(cross.length(), dot);
  92517. planeNormalTowardsCamera.copyFrom(planeNormal);
  92518. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  92519. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92520. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  92521. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  92522. }
  92523. // Flip up vector depending on which side the camera is on
  92524. if (gizmoLayer.utilityLayerScene.activeCamera) {
  92525. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  92526. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  92527. planeNormalTowardsCamera.scaleInPlace(-1);
  92528. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  92529. }
  92530. }
  92531. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  92532. if (halfCircleSide)
  92533. angle = -angle;
  92534. // Snapping logic
  92535. var snapped = false;
  92536. if (_this.snapDistance != 0) {
  92537. currentSnapDragDistance += angle;
  92538. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  92539. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  92540. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  92541. angle = _this.snapDistance * dragSteps;
  92542. snapped = true;
  92543. }
  92544. else {
  92545. angle = 0;
  92546. }
  92547. }
  92548. // If the mesh has a parent, convert needed world rotation to local rotation
  92549. tmpMatrix.reset();
  92550. if (_this.attachedMesh.parent) {
  92551. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  92552. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  92553. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  92554. }
  92555. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  92556. var quaternionCoefficient = Math.sin(angle / 2);
  92557. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  92558. // 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
  92559. if (tmpMatrix.determinant() > 0) {
  92560. amountToRotate.toEulerAnglesToRef(tmpVector);
  92561. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  92562. }
  92563. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  92564. // Rotate selected mesh quaternion over fixed axis
  92565. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  92566. }
  92567. else {
  92568. // Rotate selected mesh quaternion over rotated axis
  92569. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  92570. }
  92571. lastDragPosition.copyFrom(event.dragPlanePoint);
  92572. if (snapped) {
  92573. tmpSnapEvent.snapDistance = angle;
  92574. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  92575. }
  92576. }
  92577. });
  92578. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92579. if (_this._customMeshSet) {
  92580. return;
  92581. }
  92582. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  92583. var material = isHovered ? hoverMaterial : coloredMaterial;
  92584. _this._rootMesh.getChildMeshes().forEach(function (m) {
  92585. m.material = material;
  92586. if (m.color) {
  92587. m.color = material.emissiveColor;
  92588. }
  92589. });
  92590. });
  92591. return _this;
  92592. }
  92593. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  92594. if (this.dragBehavior) {
  92595. this.dragBehavior.enabled = value ? true : false;
  92596. }
  92597. };
  92598. /**
  92599. * Disposes of the gizmo
  92600. */
  92601. PlaneRotationGizmo.prototype.dispose = function () {
  92602. this.onSnapObservable.clear();
  92603. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92604. this.dragBehavior.detach();
  92605. _super.prototype.dispose.call(this);
  92606. };
  92607. return PlaneRotationGizmo;
  92608. }(BABYLON.Gizmo));
  92609. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  92610. })(BABYLON || (BABYLON = {}));
  92611. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  92612. var BABYLON;
  92613. (function (BABYLON) {
  92614. /**
  92615. * Gizmo that enables dragging a mesh along 3 axis
  92616. */
  92617. var PositionGizmo = /** @class */ (function (_super) {
  92618. __extends(PositionGizmo, _super);
  92619. /**
  92620. * Creates a PositionGizmo
  92621. * @param gizmoLayer The utility layer the gizmo will be added to
  92622. */
  92623. function PositionGizmo(gizmoLayer) {
  92624. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92625. var _this = _super.call(this, gizmoLayer) || this;
  92626. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92627. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92628. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92629. _this.attachedMesh = null;
  92630. return _this;
  92631. }
  92632. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  92633. set: function (mesh) {
  92634. if (this.xGizmo) {
  92635. this.xGizmo.attachedMesh = mesh;
  92636. this.yGizmo.attachedMesh = mesh;
  92637. this.zGizmo.attachedMesh = mesh;
  92638. }
  92639. },
  92640. enumerable: true,
  92641. configurable: true
  92642. });
  92643. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92644. get: function () {
  92645. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92646. },
  92647. set: function (value) {
  92648. if (this.xGizmo) {
  92649. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92650. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92651. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92652. }
  92653. },
  92654. enumerable: true,
  92655. configurable: true
  92656. });
  92657. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  92658. get: function () {
  92659. return this.xGizmo.snapDistance;
  92660. },
  92661. /**
  92662. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92663. */
  92664. set: function (value) {
  92665. if (this.xGizmo) {
  92666. this.xGizmo.snapDistance = value;
  92667. this.yGizmo.snapDistance = value;
  92668. this.zGizmo.snapDistance = value;
  92669. }
  92670. },
  92671. enumerable: true,
  92672. configurable: true
  92673. });
  92674. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  92675. get: function () {
  92676. return this.xGizmo.scaleRatio;
  92677. },
  92678. /**
  92679. * Ratio for the scale of the gizmo (Default: 1)
  92680. */
  92681. set: function (value) {
  92682. if (this.xGizmo) {
  92683. this.xGizmo.scaleRatio = value;
  92684. this.yGizmo.scaleRatio = value;
  92685. this.zGizmo.scaleRatio = value;
  92686. }
  92687. },
  92688. enumerable: true,
  92689. configurable: true
  92690. });
  92691. /**
  92692. * Disposes of the gizmo
  92693. */
  92694. PositionGizmo.prototype.dispose = function () {
  92695. this.xGizmo.dispose();
  92696. this.yGizmo.dispose();
  92697. this.zGizmo.dispose();
  92698. };
  92699. /**
  92700. * CustomMeshes are not supported by this gizmo
  92701. * @param mesh The mesh to replace the default mesh of the gizmo
  92702. */
  92703. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  92704. 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)");
  92705. };
  92706. return PositionGizmo;
  92707. }(BABYLON.Gizmo));
  92708. BABYLON.PositionGizmo = PositionGizmo;
  92709. })(BABYLON || (BABYLON = {}));
  92710. //# sourceMappingURL=babylon.positionGizmo.js.map
  92711. var BABYLON;
  92712. (function (BABYLON) {
  92713. /**
  92714. * Gizmo that enables rotating a mesh along 3 axis
  92715. */
  92716. var RotationGizmo = /** @class */ (function (_super) {
  92717. __extends(RotationGizmo, _super);
  92718. /**
  92719. * Creates a RotationGizmo
  92720. * @param gizmoLayer The utility layer the gizmo will be added to
  92721. */
  92722. function RotationGizmo(gizmoLayer) {
  92723. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92724. var _this = _super.call(this, gizmoLayer) || this;
  92725. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92726. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92727. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92728. _this.attachedMesh = null;
  92729. return _this;
  92730. }
  92731. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  92732. set: function (mesh) {
  92733. if (this.xGizmo) {
  92734. this.xGizmo.attachedMesh = mesh;
  92735. this.yGizmo.attachedMesh = mesh;
  92736. this.zGizmo.attachedMesh = mesh;
  92737. }
  92738. },
  92739. enumerable: true,
  92740. configurable: true
  92741. });
  92742. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92743. get: function () {
  92744. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92745. },
  92746. set: function (value) {
  92747. if (this.xGizmo) {
  92748. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92749. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92750. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92751. }
  92752. },
  92753. enumerable: true,
  92754. configurable: true
  92755. });
  92756. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  92757. get: function () {
  92758. return this.xGizmo.snapDistance;
  92759. },
  92760. /**
  92761. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92762. */
  92763. set: function (value) {
  92764. if (this.xGizmo) {
  92765. this.xGizmo.snapDistance = value;
  92766. this.yGizmo.snapDistance = value;
  92767. this.zGizmo.snapDistance = value;
  92768. }
  92769. },
  92770. enumerable: true,
  92771. configurable: true
  92772. });
  92773. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  92774. get: function () {
  92775. return this.xGizmo.scaleRatio;
  92776. },
  92777. /**
  92778. * Ratio for the scale of the gizmo (Default: 1)
  92779. */
  92780. set: function (value) {
  92781. if (this.xGizmo) {
  92782. this.xGizmo.scaleRatio = value;
  92783. this.yGizmo.scaleRatio = value;
  92784. this.zGizmo.scaleRatio = value;
  92785. }
  92786. },
  92787. enumerable: true,
  92788. configurable: true
  92789. });
  92790. /**
  92791. * Disposes of the gizmo
  92792. */
  92793. RotationGizmo.prototype.dispose = function () {
  92794. this.xGizmo.dispose();
  92795. this.yGizmo.dispose();
  92796. this.zGizmo.dispose();
  92797. };
  92798. /**
  92799. * CustomMeshes are not supported by this gizmo
  92800. * @param mesh The mesh to replace the default mesh of the gizmo
  92801. */
  92802. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  92803. 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)");
  92804. };
  92805. return RotationGizmo;
  92806. }(BABYLON.Gizmo));
  92807. BABYLON.RotationGizmo = RotationGizmo;
  92808. })(BABYLON || (BABYLON = {}));
  92809. //# sourceMappingURL=babylon.rotationGizmo.js.map
  92810. var BABYLON;
  92811. (function (BABYLON) {
  92812. /**
  92813. * Gizmo that enables scaling a mesh along 3 axis
  92814. */
  92815. var ScaleGizmo = /** @class */ (function (_super) {
  92816. __extends(ScaleGizmo, _super);
  92817. /**
  92818. * Creates a ScaleGizmo
  92819. * @param gizmoLayer The utility layer the gizmo will be added to
  92820. */
  92821. function ScaleGizmo(gizmoLayer) {
  92822. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92823. var _this = _super.call(this, gizmoLayer) || this;
  92824. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92825. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92826. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92827. // Create uniform scale gizmo
  92828. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  92829. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92830. _this._uniformGizmo.uniformScaling = true;
  92831. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  92832. octahedron.scaling.scaleInPlace(0.007);
  92833. _this._uniformGizmo.setCustomMesh(octahedron, true);
  92834. _this.attachedMesh = null;
  92835. return _this;
  92836. }
  92837. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  92838. set: function (mesh) {
  92839. if (this.xGizmo) {
  92840. this.xGizmo.attachedMesh = mesh;
  92841. this.yGizmo.attachedMesh = mesh;
  92842. this.zGizmo.attachedMesh = mesh;
  92843. this._uniformGizmo.attachedMesh = mesh;
  92844. }
  92845. },
  92846. enumerable: true,
  92847. configurable: true
  92848. });
  92849. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92850. get: function () {
  92851. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92852. },
  92853. set: function (value) {
  92854. if (this.xGizmo) {
  92855. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92856. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92857. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92858. }
  92859. },
  92860. enumerable: true,
  92861. configurable: true
  92862. });
  92863. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  92864. get: function () {
  92865. return this.xGizmo.snapDistance;
  92866. },
  92867. /**
  92868. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92869. */
  92870. set: function (value) {
  92871. if (this.xGizmo) {
  92872. this.xGizmo.snapDistance = value;
  92873. this.yGizmo.snapDistance = value;
  92874. this.zGizmo.snapDistance = value;
  92875. this._uniformGizmo.snapDistance = value;
  92876. }
  92877. },
  92878. enumerable: true,
  92879. configurable: true
  92880. });
  92881. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  92882. get: function () {
  92883. return this.xGizmo.scaleRatio;
  92884. },
  92885. /**
  92886. * Ratio for the scale of the gizmo (Default: 1)
  92887. */
  92888. set: function (value) {
  92889. if (this.xGizmo) {
  92890. this.xGizmo.scaleRatio = value;
  92891. this.yGizmo.scaleRatio = value;
  92892. this.zGizmo.scaleRatio = value;
  92893. this._uniformGizmo.scaleRatio = value;
  92894. }
  92895. },
  92896. enumerable: true,
  92897. configurable: true
  92898. });
  92899. /**
  92900. * Disposes of the gizmo
  92901. */
  92902. ScaleGizmo.prototype.dispose = function () {
  92903. this.xGizmo.dispose();
  92904. this.yGizmo.dispose();
  92905. this.zGizmo.dispose();
  92906. this._uniformGizmo.dispose();
  92907. };
  92908. return ScaleGizmo;
  92909. }(BABYLON.Gizmo));
  92910. BABYLON.ScaleGizmo = ScaleGizmo;
  92911. })(BABYLON || (BABYLON = {}));
  92912. //# sourceMappingURL=babylon.scaleGizmo.js.map
  92913. var BABYLON;
  92914. (function (BABYLON) {
  92915. /**
  92916. * Bounding box gizmo
  92917. */
  92918. var BoundingBoxGizmo = /** @class */ (function (_super) {
  92919. __extends(BoundingBoxGizmo, _super);
  92920. /**
  92921. * Creates an BoundingBoxGizmo
  92922. * @param gizmoLayer The utility layer the gizmo will be added to
  92923. * @param color The color of the gizmo
  92924. */
  92925. function BoundingBoxGizmo(color, gizmoLayer) {
  92926. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92927. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  92928. var _this = _super.call(this, gizmoLayer) || this;
  92929. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  92930. _this._renderObserver = null;
  92931. _this._pointerObserver = null;
  92932. _this._scaleDragSpeed = 0.2;
  92933. _this._tmpQuaternion = new BABYLON.Quaternion();
  92934. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92935. _this._tmpRotationMatrix = new BABYLON.Matrix();
  92936. /**
  92937. * 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)
  92938. */
  92939. _this.ignoreChildren = false;
  92940. /**
  92941. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  92942. */
  92943. _this.rotationSphereSize = 0.1;
  92944. /**
  92945. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  92946. */
  92947. _this.scaleBoxSize = 0.1;
  92948. /**
  92949. * 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)
  92950. */
  92951. _this.fixedDragMeshScreenSize = false;
  92952. /**
  92953. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  92954. */
  92955. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  92956. /**
  92957. * Fired when a rotation sphere or scale box is dragged
  92958. */
  92959. _this.onDragStartObservable = new BABYLON.Observable();
  92960. /**
  92961. * Fired when a scale box is dragged
  92962. */
  92963. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  92964. /**
  92965. * Fired when a scale box drag is ended
  92966. */
  92967. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  92968. /**
  92969. * Fired when a rotation sphere is dragged
  92970. */
  92971. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  92972. /**
  92973. * Fired when a rotation sphere drag is ended
  92974. */
  92975. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  92976. /**
  92977. * 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)
  92978. */
  92979. _this.scalePivot = null;
  92980. _this._existingMeshScale = new BABYLON.Vector3();
  92981. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  92982. // store/remove pivot point should only be applied during their outermost calls
  92983. _this._pivotCached = 0;
  92984. _this._oldPivotPoint = new BABYLON.Vector3();
  92985. _this._pivotTranslation = new BABYLON.Vector3();
  92986. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  92987. _this._updateScale = false;
  92988. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  92989. // Create Materials
  92990. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92991. coloredMaterial.disableLighting = true;
  92992. coloredMaterial.emissiveColor = color;
  92993. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92994. hoverColoredMaterial.disableLighting = true;
  92995. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92996. // Build bounding box out of lines
  92997. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92998. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  92999. var lines = [];
  93000. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  93001. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  93002. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  93003. 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));
  93004. 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));
  93005. 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));
  93006. 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));
  93007. 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));
  93008. 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));
  93009. 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));
  93010. 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));
  93011. 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));
  93012. lines.forEach(function (l) {
  93013. l.color = color;
  93014. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  93015. l.isPickable = false;
  93016. _this._lineBoundingBox.addChild(l);
  93017. });
  93018. _this._rootMesh.addChild(_this._lineBoundingBox);
  93019. // Create rotation spheres
  93020. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93021. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  93022. var _loop_1 = function (i_1) {
  93023. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  93024. sphere.rotationQuaternion = new BABYLON.Quaternion();
  93025. sphere.material = coloredMaterial;
  93026. // Drag behavior
  93027. _dragBehavior = new BABYLON.PointerDragBehavior({});
  93028. _dragBehavior.moveAttached = false;
  93029. _dragBehavior.updateDragPlane = false;
  93030. sphere.addBehavior(_dragBehavior);
  93031. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  93032. var totalTurnAmountOfDrag = 0;
  93033. _dragBehavior.onDragStartObservable.add(function (event) {
  93034. startingTurnDirection.copyFrom(sphere.forward);
  93035. totalTurnAmountOfDrag = 0;
  93036. });
  93037. _dragBehavior.onDragObservable.add(function (event) {
  93038. _this.onRotationSphereDragObservable.notifyObservers({});
  93039. if (_this.attachedMesh) {
  93040. _this.removeAndStorePivotPoint();
  93041. var worldDragDirection = startingTurnDirection;
  93042. // Project the world right on to the drag plane
  93043. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  93044. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  93045. // project drag delta on to the resulting drag axis and rotate based on that
  93046. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  93047. // Make rotation relative to size of mesh.
  93048. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93049. // Rotate based on axis
  93050. if (!_this.attachedMesh.rotationQuaternion) {
  93051. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93052. }
  93053. if (!_this._anchorMesh.rotationQuaternion) {
  93054. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  93055. }
  93056. // Do not allow the object to turn more than a full circle
  93057. totalTurnAmountOfDrag += projectDist;
  93058. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  93059. if (i_1 >= 8) {
  93060. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  93061. }
  93062. else if (i_1 >= 4) {
  93063. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  93064. }
  93065. else {
  93066. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  93067. }
  93068. // Rotate around center of bounding box
  93069. _this._anchorMesh.addChild(_this.attachedMesh);
  93070. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  93071. _this._anchorMesh.removeChild(_this.attachedMesh);
  93072. }
  93073. _this.updateBoundingBox();
  93074. _this.restorePivotPoint();
  93075. }
  93076. });
  93077. // Selection/deselection
  93078. _dragBehavior.onDragStartObservable.add(function () {
  93079. _this.onDragStartObservable.notifyObservers({});
  93080. _this._selectNode(sphere);
  93081. });
  93082. _dragBehavior.onDragEndObservable.add(function () {
  93083. _this.onRotationSphereDragEndObservable.notifyObservers({});
  93084. _this._selectNode(null);
  93085. });
  93086. this_1._rotateSpheresParent.addChild(sphere);
  93087. };
  93088. var this_1 = this, _dragBehavior;
  93089. for (var i_1 = 0; i_1 < 12; i_1++) {
  93090. _loop_1(i_1);
  93091. }
  93092. _this._rootMesh.addChild(_this._rotateSpheresParent);
  93093. // Create scale cubes
  93094. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93095. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  93096. for (var i = 0; i < 2; i++) {
  93097. for (var j = 0; j < 2; j++) {
  93098. var _loop_2 = function () {
  93099. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  93100. box.material = coloredMaterial;
  93101. // Dragging logic
  93102. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  93103. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93104. _dragBehavior.moveAttached = false;
  93105. box.addBehavior(_dragBehavior);
  93106. _dragBehavior.onDragObservable.add(function (event) {
  93107. _this.onScaleBoxDragObservable.notifyObservers({});
  93108. if (_this.attachedMesh) {
  93109. _this.removeAndStorePivotPoint();
  93110. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  93111. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  93112. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  93113. _this.updateBoundingBox();
  93114. if (_this.scalePivot) {
  93115. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  93116. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  93117. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  93118. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93119. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93120. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  93121. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  93122. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  93123. }
  93124. else {
  93125. // Scale from the position of the opposite corner
  93126. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  93127. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  93128. }
  93129. _this._anchorMesh.addChild(_this.attachedMesh);
  93130. _this._anchorMesh.scaling.addInPlace(deltaScale);
  93131. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  93132. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  93133. }
  93134. _this._anchorMesh.removeChild(_this.attachedMesh);
  93135. _this.restorePivotPoint();
  93136. }
  93137. });
  93138. // Selection/deselection
  93139. _dragBehavior.onDragStartObservable.add(function () {
  93140. _this.onDragStartObservable.notifyObservers({});
  93141. _this._selectNode(box);
  93142. });
  93143. _dragBehavior.onDragEndObservable.add(function () {
  93144. _this.onScaleBoxDragEndObservable.notifyObservers({});
  93145. _this._selectNode(null);
  93146. });
  93147. this_2._scaleBoxesParent.addChild(box);
  93148. };
  93149. var this_2 = this, _dragBehavior;
  93150. for (var k = 0; k < 2; k++) {
  93151. _loop_2();
  93152. }
  93153. }
  93154. }
  93155. _this._rootMesh.addChild(_this._scaleBoxesParent);
  93156. // Hover color change
  93157. var pointerIds = new Array();
  93158. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93159. if (!pointerIds[pointerInfo.event.pointerId]) {
  93160. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  93161. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  93162. pointerIds[pointerInfo.event.pointerId] = mesh;
  93163. mesh.material = hoverColoredMaterial;
  93164. }
  93165. });
  93166. }
  93167. else {
  93168. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  93169. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  93170. delete pointerIds[pointerInfo.event.pointerId];
  93171. }
  93172. }
  93173. });
  93174. // Update bounding box positions
  93175. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  93176. // Only update the bouding box if scaling has changed
  93177. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  93178. _this.updateBoundingBox();
  93179. }
  93180. });
  93181. _this.updateBoundingBox();
  93182. return _this;
  93183. }
  93184. BoundingBoxGizmo.prototype.removeAndStorePivotPoint = function () {
  93185. if (this.attachedMesh && this._pivotCached === 0) {
  93186. // Save old pivot and set pivot to 0,0,0
  93187. this.attachedMesh.getPivotPointToRef(this._oldPivotPoint);
  93188. if (this._oldPivotPoint.equalsToFloats(0, 0, 0)) {
  93189. return;
  93190. }
  93191. this.attachedMesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  93192. this._oldPivotPoint.subtractToRef(this.attachedMesh.getPivotPoint(), this._pivotTranslation);
  93193. this._tmpVector.copyFromFloats(1, 1, 1);
  93194. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93195. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93196. this.attachedMesh.position.addInPlace(this._tmpVector);
  93197. }
  93198. this._pivotCached++;
  93199. };
  93200. BoundingBoxGizmo.prototype.restorePivotPoint = function () {
  93201. if (this.attachedMesh && !this._oldPivotPoint.equalsToFloats(0, 0, 0) && this._pivotCached === 1) {
  93202. this.attachedMesh.setPivotPoint(this._oldPivotPoint);
  93203. this._tmpVector.copyFromFloats(1, 1, 1);
  93204. this._tmpVector.subtractInPlace(this.attachedMesh.scaling);
  93205. this._tmpVector.multiplyInPlace(this._pivotTranslation);
  93206. this.attachedMesh.position.subtractInPlace(this._tmpVector);
  93207. }
  93208. this._pivotCached--;
  93209. };
  93210. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  93211. if (value) {
  93212. // Reset anchor mesh to match attached mesh's scale
  93213. // This is needed to avoid invalid box/sphere position on first drag
  93214. this._anchorMesh.addChild(value);
  93215. this._anchorMesh.removeChild(value);
  93216. this.updateBoundingBox();
  93217. }
  93218. };
  93219. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  93220. this._rotateSpheresParent.getChildMeshes()
  93221. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  93222. m.isVisible = (!selectedMesh || m == selectedMesh);
  93223. });
  93224. };
  93225. BoundingBoxGizmo.prototype._recurseComputeWorld = function (node) {
  93226. var _this = this;
  93227. node.computeWorldMatrix(true);
  93228. if (!this.ignoreChildren) {
  93229. node.getDescendants().forEach(function (n) {
  93230. _this._recurseComputeWorld(n);
  93231. });
  93232. }
  93233. };
  93234. /**
  93235. * Updates the bounding box information for the Gizmo
  93236. */
  93237. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  93238. if (this.attachedMesh) {
  93239. this.removeAndStorePivotPoint();
  93240. this._update();
  93241. // Rotate based on axis
  93242. if (!this.attachedMesh.rotationQuaternion) {
  93243. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  93244. }
  93245. if (!this._anchorMesh.rotationQuaternion) {
  93246. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  93247. }
  93248. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93249. // Store original position and reset mesh to origin before computing the bounding box
  93250. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  93251. this._tmpVector.copyFrom(this.attachedMesh.position);
  93252. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  93253. this.attachedMesh.position.set(0, 0, 0);
  93254. // Update bounding dimensions/positions
  93255. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  93256. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  93257. // Update gizmo to match bounding box scaling and rotation
  93258. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  93259. 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);
  93260. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  93261. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  93262. this._lineBoundingBox.computeWorldMatrix();
  93263. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  93264. // restore position/rotation values
  93265. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  93266. this.attachedMesh.position.copyFrom(this._tmpVector);
  93267. this._recurseComputeWorld(this.attachedMesh);
  93268. }
  93269. // Update rotation sphere locations
  93270. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  93271. for (var i = 0; i < 3; i++) {
  93272. for (var j = 0; j < 2; j++) {
  93273. for (var k = 0; k < 2; k++) {
  93274. var index = ((i * 4) + (j * 2)) + k;
  93275. if (i == 0) {
  93276. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93277. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93278. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93279. }
  93280. if (i == 1) {
  93281. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  93282. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93283. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93284. }
  93285. if (i == 2) {
  93286. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  93287. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93288. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  93289. }
  93290. if (this.fixedDragMeshScreenSize) {
  93291. this._rootMesh.computeWorldMatrix();
  93292. this._rotateSpheresParent.computeWorldMatrix();
  93293. rotateSpheres[index].computeWorldMatrix();
  93294. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93295. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93296. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93297. }
  93298. else {
  93299. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  93300. }
  93301. }
  93302. }
  93303. }
  93304. // Update scale box locations
  93305. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  93306. for (var i = 0; i < 2; i++) {
  93307. for (var j = 0; j < 2; j++) {
  93308. for (var k = 0; k < 2; k++) {
  93309. var index = ((i * 4) + (j * 2)) + k;
  93310. if (scaleBoxes[index]) {
  93311. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  93312. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  93313. if (this.fixedDragMeshScreenSize) {
  93314. this._rootMesh.computeWorldMatrix();
  93315. this._scaleBoxesParent.computeWorldMatrix();
  93316. scaleBoxes[index].computeWorldMatrix();
  93317. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  93318. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  93319. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  93320. }
  93321. else {
  93322. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  93323. }
  93324. }
  93325. }
  93326. }
  93327. }
  93328. if (this.attachedMesh) {
  93329. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  93330. this.restorePivotPoint();
  93331. }
  93332. };
  93333. /**
  93334. * Enables rotation on the specified axis and disables rotation on the others
  93335. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  93336. */
  93337. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  93338. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  93339. if (i < 4) {
  93340. m.setEnabled(axis.indexOf("x") != -1);
  93341. }
  93342. else if (i < 8) {
  93343. m.setEnabled(axis.indexOf("y") != -1);
  93344. }
  93345. else {
  93346. m.setEnabled(axis.indexOf("z") != -1);
  93347. }
  93348. });
  93349. };
  93350. /**
  93351. * Disposes of the gizmo
  93352. */
  93353. BoundingBoxGizmo.prototype.dispose = function () {
  93354. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93355. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  93356. this._lineBoundingBox.dispose();
  93357. this._rotateSpheresParent.dispose();
  93358. this._scaleBoxesParent.dispose();
  93359. _super.prototype.dispose.call(this);
  93360. };
  93361. /**
  93362. * 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)
  93363. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  93364. * @returns the bounding box mesh with the passed in mesh as a child
  93365. */
  93366. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  93367. var makeNotPickable = function (root) {
  93368. root.isPickable = false;
  93369. root.getChildMeshes().forEach(function (c) {
  93370. makeNotPickable(c);
  93371. });
  93372. };
  93373. makeNotPickable(mesh);
  93374. // Reset position to get boudning box from origin with no rotation
  93375. if (!mesh.rotationQuaternion) {
  93376. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  93377. }
  93378. var oldPos = mesh.position.clone();
  93379. var oldRot = mesh.rotationQuaternion.clone();
  93380. mesh.rotationQuaternion.set(0, 0, 0, 1);
  93381. mesh.position.set(0, 0, 0);
  93382. // Update bounding dimensions/positions
  93383. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  93384. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  93385. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  93386. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  93387. // Restore original positions
  93388. mesh.addChild(box);
  93389. mesh.rotationQuaternion.copyFrom(oldRot);
  93390. mesh.position.copyFrom(oldPos);
  93391. // Reverse parenting
  93392. mesh.removeChild(box);
  93393. box.addChild(mesh);
  93394. box.visibility = 0;
  93395. return box;
  93396. };
  93397. /**
  93398. * CustomMeshes are not supported by this gizmo
  93399. * @param mesh The mesh to replace the default mesh of the gizmo
  93400. */
  93401. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  93402. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  93403. };
  93404. return BoundingBoxGizmo;
  93405. }(BABYLON.Gizmo));
  93406. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  93407. })(BABYLON || (BABYLON = {}));
  93408. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  93409. var BABYLON;
  93410. (function (BABYLON) {
  93411. /**
  93412. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  93413. */
  93414. var GizmoManager = /** @class */ (function () {
  93415. /**
  93416. * Instatiates a gizmo manager
  93417. * @param scene the scene to overlay the gizmos on top of
  93418. */
  93419. function GizmoManager(scene) {
  93420. var _this = this;
  93421. this.scene = scene;
  93422. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  93423. this._pointerObserver = null;
  93424. this._attachedMesh = null;
  93425. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  93426. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  93427. /**
  93428. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  93429. */
  93430. this.attachableMeshes = null;
  93431. /**
  93432. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  93433. */
  93434. this.usePointerToAttachGizmos = true;
  93435. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  93436. // Instatiate/dispose gizmos based on pointer actions
  93437. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  93438. if (!_this.usePointerToAttachGizmos) {
  93439. return;
  93440. }
  93441. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  93442. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  93443. var node = pointerInfo.pickInfo.pickedMesh;
  93444. if (_this.attachableMeshes == null) {
  93445. // Attach to the most parent node
  93446. while (node && node.parent != null) {
  93447. node = node.parent;
  93448. }
  93449. }
  93450. else {
  93451. // Attach to the parent node that is an attachableMesh
  93452. var found = false;
  93453. _this.attachableMeshes.forEach(function (mesh) {
  93454. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  93455. node = mesh;
  93456. found = true;
  93457. }
  93458. });
  93459. if (!found) {
  93460. node = null;
  93461. }
  93462. }
  93463. if (node instanceof BABYLON.AbstractMesh) {
  93464. _this.attachToMesh(node);
  93465. }
  93466. else {
  93467. _this.attachToMesh(null);
  93468. }
  93469. }
  93470. else {
  93471. _this.attachToMesh(null);
  93472. }
  93473. }
  93474. });
  93475. }
  93476. /**
  93477. * Attaches a set of gizmos to the specified mesh
  93478. * @param mesh The mesh the gizmo's should be attached to
  93479. */
  93480. GizmoManager.prototype.attachToMesh = function (mesh) {
  93481. if (this._attachedMesh) {
  93482. this._attachedMesh.removeBehavior(this._dragBehavior);
  93483. }
  93484. this._attachedMesh = mesh;
  93485. for (var key in this.gizmos) {
  93486. var gizmo = (this.gizmos[key]);
  93487. if (gizmo && this._gizmosEnabled[key]) {
  93488. gizmo.attachedMesh = mesh;
  93489. }
  93490. }
  93491. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  93492. this._attachedMesh.addBehavior(this._dragBehavior);
  93493. }
  93494. };
  93495. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  93496. get: function () {
  93497. return this._gizmosEnabled.positionGizmo;
  93498. },
  93499. /**
  93500. * If the position gizmo is enabled
  93501. */
  93502. set: function (value) {
  93503. if (value) {
  93504. if (!this.gizmos.positionGizmo) {
  93505. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  93506. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93507. }
  93508. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  93509. }
  93510. else if (this.gizmos.positionGizmo) {
  93511. this.gizmos.positionGizmo.attachedMesh = null;
  93512. }
  93513. this._gizmosEnabled.positionGizmo = value;
  93514. },
  93515. enumerable: true,
  93516. configurable: true
  93517. });
  93518. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  93519. get: function () {
  93520. return this._gizmosEnabled.rotationGizmo;
  93521. },
  93522. /**
  93523. * If the rotation gizmo is enabled
  93524. */
  93525. set: function (value) {
  93526. if (value) {
  93527. if (!this.gizmos.rotationGizmo) {
  93528. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  93529. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  93530. }
  93531. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  93532. }
  93533. else if (this.gizmos.rotationGizmo) {
  93534. this.gizmos.rotationGizmo.attachedMesh = null;
  93535. }
  93536. this._gizmosEnabled.rotationGizmo = value;
  93537. },
  93538. enumerable: true,
  93539. configurable: true
  93540. });
  93541. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  93542. get: function () {
  93543. return this._gizmosEnabled.scaleGizmo;
  93544. },
  93545. /**
  93546. * If the scale gizmo is enabled
  93547. */
  93548. set: function (value) {
  93549. if (value) {
  93550. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  93551. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  93552. }
  93553. else if (this.gizmos.scaleGizmo) {
  93554. this.gizmos.scaleGizmo.attachedMesh = null;
  93555. }
  93556. this._gizmosEnabled.scaleGizmo = value;
  93557. },
  93558. enumerable: true,
  93559. configurable: true
  93560. });
  93561. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  93562. get: function () {
  93563. return this._gizmosEnabled.boundingBoxGizmo;
  93564. },
  93565. /**
  93566. * If the boundingBox gizmo is enabled
  93567. */
  93568. set: function (value) {
  93569. if (value) {
  93570. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  93571. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  93572. if (this._attachedMesh) {
  93573. this._attachedMesh.removeBehavior(this._dragBehavior);
  93574. this._attachedMesh.addBehavior(this._dragBehavior);
  93575. }
  93576. }
  93577. else if (this.gizmos.boundingBoxGizmo) {
  93578. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  93579. }
  93580. this._gizmosEnabled.boundingBoxGizmo = value;
  93581. },
  93582. enumerable: true,
  93583. configurable: true
  93584. });
  93585. /**
  93586. * Disposes of the gizmo manager
  93587. */
  93588. GizmoManager.prototype.dispose = function () {
  93589. this.scene.onPointerObservable.remove(this._pointerObserver);
  93590. for (var key in this.gizmos) {
  93591. var gizmo = (this.gizmos[key]);
  93592. if (gizmo) {
  93593. gizmo.dispose();
  93594. }
  93595. }
  93596. this._dragBehavior.detach();
  93597. };
  93598. return GizmoManager;
  93599. }());
  93600. BABYLON.GizmoManager = GizmoManager;
  93601. })(BABYLON || (BABYLON = {}));
  93602. //# sourceMappingURL=babylon.gizmoManager.js.map
  93603. var BABYLON;
  93604. (function (BABYLON) {
  93605. /**
  93606. * Defines a target to use with MorphTargetManager
  93607. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93608. */
  93609. var MorphTarget = /** @class */ (function () {
  93610. /**
  93611. * Creates a new MorphTarget
  93612. * @param name defines the name of the target
  93613. * @param influence defines the influence to use
  93614. */
  93615. function MorphTarget(
  93616. /** defines the name of the target */
  93617. name, influence, scene) {
  93618. if (influence === void 0) { influence = 0; }
  93619. if (scene === void 0) { scene = null; }
  93620. this.name = name;
  93621. /**
  93622. * Gets or sets the list of animations
  93623. */
  93624. this.animations = new Array();
  93625. this._positions = null;
  93626. this._normals = null;
  93627. this._tangents = null;
  93628. /**
  93629. * Observable raised when the influence changes
  93630. */
  93631. this.onInfluenceChanged = new BABYLON.Observable();
  93632. this._animationPropertiesOverride = null;
  93633. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93634. this.influence = influence;
  93635. }
  93636. Object.defineProperty(MorphTarget.prototype, "influence", {
  93637. /**
  93638. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  93639. */
  93640. get: function () {
  93641. return this._influence;
  93642. },
  93643. set: function (influence) {
  93644. if (this._influence === influence) {
  93645. return;
  93646. }
  93647. var previous = this._influence;
  93648. this._influence = influence;
  93649. if (this.onInfluenceChanged.hasObservers) {
  93650. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  93651. }
  93652. },
  93653. enumerable: true,
  93654. configurable: true
  93655. });
  93656. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  93657. /**
  93658. * Gets or sets the animation properties override
  93659. */
  93660. get: function () {
  93661. if (!this._animationPropertiesOverride && this._scene) {
  93662. return this._scene.animationPropertiesOverride;
  93663. }
  93664. return this._animationPropertiesOverride;
  93665. },
  93666. set: function (value) {
  93667. this._animationPropertiesOverride = value;
  93668. },
  93669. enumerable: true,
  93670. configurable: true
  93671. });
  93672. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  93673. /**
  93674. * Gets a boolean defining if the target contains position data
  93675. */
  93676. get: function () {
  93677. return !!this._positions;
  93678. },
  93679. enumerable: true,
  93680. configurable: true
  93681. });
  93682. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  93683. /**
  93684. * Gets a boolean defining if the target contains normal data
  93685. */
  93686. get: function () {
  93687. return !!this._normals;
  93688. },
  93689. enumerable: true,
  93690. configurable: true
  93691. });
  93692. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  93693. /**
  93694. * Gets a boolean defining if the target contains tangent data
  93695. */
  93696. get: function () {
  93697. return !!this._tangents;
  93698. },
  93699. enumerable: true,
  93700. configurable: true
  93701. });
  93702. /**
  93703. * Affects position data to this target
  93704. * @param data defines the position data to use
  93705. */
  93706. MorphTarget.prototype.setPositions = function (data) {
  93707. this._positions = data;
  93708. };
  93709. /**
  93710. * Gets the position data stored in this target
  93711. * @returns a FloatArray containing the position data (or null if not present)
  93712. */
  93713. MorphTarget.prototype.getPositions = function () {
  93714. return this._positions;
  93715. };
  93716. /**
  93717. * Affects normal data to this target
  93718. * @param data defines the normal data to use
  93719. */
  93720. MorphTarget.prototype.setNormals = function (data) {
  93721. this._normals = data;
  93722. };
  93723. /**
  93724. * Gets the normal data stored in this target
  93725. * @returns a FloatArray containing the normal data (or null if not present)
  93726. */
  93727. MorphTarget.prototype.getNormals = function () {
  93728. return this._normals;
  93729. };
  93730. /**
  93731. * Affects tangent data to this target
  93732. * @param data defines the tangent data to use
  93733. */
  93734. MorphTarget.prototype.setTangents = function (data) {
  93735. this._tangents = data;
  93736. };
  93737. /**
  93738. * Gets the tangent data stored in this target
  93739. * @returns a FloatArray containing the tangent data (or null if not present)
  93740. */
  93741. MorphTarget.prototype.getTangents = function () {
  93742. return this._tangents;
  93743. };
  93744. /**
  93745. * Serializes the current target into a Serialization object
  93746. * @returns the serialized object
  93747. */
  93748. MorphTarget.prototype.serialize = function () {
  93749. var serializationObject = {};
  93750. serializationObject.name = this.name;
  93751. serializationObject.influence = this.influence;
  93752. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  93753. if (this.hasNormals) {
  93754. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  93755. }
  93756. if (this.hasTangents) {
  93757. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  93758. }
  93759. // Animations
  93760. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  93761. return serializationObject;
  93762. };
  93763. // Statics
  93764. /**
  93765. * Creates a new target from serialized data
  93766. * @param serializationObject defines the serialized data to use
  93767. * @returns a new MorphTarget
  93768. */
  93769. MorphTarget.Parse = function (serializationObject) {
  93770. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  93771. result.setPositions(serializationObject.positions);
  93772. if (serializationObject.normals) {
  93773. result.setNormals(serializationObject.normals);
  93774. }
  93775. if (serializationObject.tangents) {
  93776. result.setTangents(serializationObject.tangents);
  93777. }
  93778. // Animations
  93779. if (serializationObject.animations) {
  93780. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  93781. var parsedAnimation = serializationObject.animations[animationIndex];
  93782. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  93783. }
  93784. }
  93785. return result;
  93786. };
  93787. /**
  93788. * Creates a MorphTarget from mesh data
  93789. * @param mesh defines the source mesh
  93790. * @param name defines the name to use for the new target
  93791. * @param influence defines the influence to attach to the target
  93792. * @returns a new MorphTarget
  93793. */
  93794. MorphTarget.FromMesh = function (mesh, name, influence) {
  93795. if (!name) {
  93796. name = mesh.name;
  93797. }
  93798. var result = new MorphTarget(name, influence, mesh.getScene());
  93799. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93800. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93801. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  93802. }
  93803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  93804. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  93805. }
  93806. return result;
  93807. };
  93808. return MorphTarget;
  93809. }());
  93810. BABYLON.MorphTarget = MorphTarget;
  93811. })(BABYLON || (BABYLON = {}));
  93812. //# sourceMappingURL=babylon.morphTarget.js.map
  93813. var BABYLON;
  93814. (function (BABYLON) {
  93815. /**
  93816. * This class is used to deform meshes using morphing between different targets
  93817. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93818. */
  93819. var MorphTargetManager = /** @class */ (function () {
  93820. /**
  93821. * Creates a new MorphTargetManager
  93822. * @param scene defines the current scene
  93823. */
  93824. function MorphTargetManager(scene) {
  93825. if (scene === void 0) { scene = null; }
  93826. this._targets = new Array();
  93827. this._targetObservable = new Array();
  93828. this._activeTargets = new BABYLON.SmartArray(16);
  93829. this._supportsNormals = false;
  93830. this._supportsTangents = false;
  93831. this._vertexCount = 0;
  93832. this._uniqueId = 0;
  93833. this._tempInfluences = new Array();
  93834. if (!scene) {
  93835. scene = BABYLON.Engine.LastCreatedScene;
  93836. }
  93837. this._scene = scene;
  93838. if (this._scene) {
  93839. this._scene.morphTargetManagers.push(this);
  93840. this._uniqueId = this._scene.getUniqueId();
  93841. }
  93842. }
  93843. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  93844. /**
  93845. * Gets the unique ID of this manager
  93846. */
  93847. get: function () {
  93848. return this._uniqueId;
  93849. },
  93850. enumerable: true,
  93851. configurable: true
  93852. });
  93853. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  93854. /**
  93855. * Gets the number of vertices handled by this manager
  93856. */
  93857. get: function () {
  93858. return this._vertexCount;
  93859. },
  93860. enumerable: true,
  93861. configurable: true
  93862. });
  93863. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  93864. /**
  93865. * Gets a boolean indicating if this manager supports morphing of normals
  93866. */
  93867. get: function () {
  93868. return this._supportsNormals;
  93869. },
  93870. enumerable: true,
  93871. configurable: true
  93872. });
  93873. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  93874. /**
  93875. * Gets a boolean indicating if this manager supports morphing of tangents
  93876. */
  93877. get: function () {
  93878. return this._supportsTangents;
  93879. },
  93880. enumerable: true,
  93881. configurable: true
  93882. });
  93883. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  93884. /**
  93885. * Gets the number of targets stored in this manager
  93886. */
  93887. get: function () {
  93888. return this._targets.length;
  93889. },
  93890. enumerable: true,
  93891. configurable: true
  93892. });
  93893. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  93894. /**
  93895. * Gets the number of influencers (ie. the number of targets with influences > 0)
  93896. */
  93897. get: function () {
  93898. return this._activeTargets.length;
  93899. },
  93900. enumerable: true,
  93901. configurable: true
  93902. });
  93903. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  93904. /**
  93905. * Gets the list of influences (one per target)
  93906. */
  93907. get: function () {
  93908. return this._influences;
  93909. },
  93910. enumerable: true,
  93911. configurable: true
  93912. });
  93913. /**
  93914. * Gets the active target at specified index. An active target is a target with an influence > 0
  93915. * @param index defines the index to check
  93916. * @returns the requested target
  93917. */
  93918. MorphTargetManager.prototype.getActiveTarget = function (index) {
  93919. return this._activeTargets.data[index];
  93920. };
  93921. /**
  93922. * Gets the target at specified index
  93923. * @param index defines the index to check
  93924. * @returns the requested target
  93925. */
  93926. MorphTargetManager.prototype.getTarget = function (index) {
  93927. return this._targets[index];
  93928. };
  93929. /**
  93930. * Add a new target to this manager
  93931. * @param target defines the target to add
  93932. */
  93933. MorphTargetManager.prototype.addTarget = function (target) {
  93934. var _this = this;
  93935. this._targets.push(target);
  93936. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  93937. _this._syncActiveTargets(needUpdate);
  93938. }));
  93939. this._syncActiveTargets(true);
  93940. };
  93941. /**
  93942. * Removes a target from the manager
  93943. * @param target defines the target to remove
  93944. */
  93945. MorphTargetManager.prototype.removeTarget = function (target) {
  93946. var index = this._targets.indexOf(target);
  93947. if (index >= 0) {
  93948. this._targets.splice(index, 1);
  93949. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  93950. this._syncActiveTargets(true);
  93951. }
  93952. };
  93953. /**
  93954. * Serializes the current manager into a Serialization object
  93955. * @returns the serialized object
  93956. */
  93957. MorphTargetManager.prototype.serialize = function () {
  93958. var serializationObject = {};
  93959. serializationObject.id = this.uniqueId;
  93960. serializationObject.targets = [];
  93961. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93962. var target = _a[_i];
  93963. serializationObject.targets.push(target.serialize());
  93964. }
  93965. return serializationObject;
  93966. };
  93967. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  93968. var influenceCount = 0;
  93969. this._activeTargets.reset();
  93970. this._supportsNormals = true;
  93971. this._supportsTangents = true;
  93972. this._vertexCount = 0;
  93973. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93974. var target = _a[_i];
  93975. this._activeTargets.push(target);
  93976. this._tempInfluences[influenceCount++] = target.influence;
  93977. var positions = target.getPositions();
  93978. if (positions) {
  93979. this._supportsNormals = this._supportsNormals && target.hasNormals;
  93980. this._supportsTangents = this._supportsTangents && target.hasTangents;
  93981. var vertexCount = positions.length / 3;
  93982. if (this._vertexCount === 0) {
  93983. this._vertexCount = vertexCount;
  93984. }
  93985. else if (this._vertexCount !== vertexCount) {
  93986. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  93987. return;
  93988. }
  93989. }
  93990. }
  93991. if (!this._influences || this._influences.length !== influenceCount) {
  93992. this._influences = new Float32Array(influenceCount);
  93993. }
  93994. for (var index = 0; index < influenceCount; index++) {
  93995. this._influences[index] = this._tempInfluences[index];
  93996. }
  93997. if (needUpdate) {
  93998. this.synchronize();
  93999. }
  94000. };
  94001. /**
  94002. * Syncrhonize the targets with all the meshes using this morph target manager
  94003. */
  94004. MorphTargetManager.prototype.synchronize = function () {
  94005. if (!this._scene) {
  94006. return;
  94007. }
  94008. // Flag meshes as dirty to resync with the active targets
  94009. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  94010. var mesh = _a[_i];
  94011. if (mesh.morphTargetManager === this) {
  94012. mesh._syncGeometryWithMorphTargetManager();
  94013. }
  94014. }
  94015. };
  94016. // Statics
  94017. /**
  94018. * Creates a new MorphTargetManager from serialized data
  94019. * @param serializationObject defines the serialized data
  94020. * @param scene defines the hosting scene
  94021. * @returns the new MorphTargetManager
  94022. */
  94023. MorphTargetManager.Parse = function (serializationObject, scene) {
  94024. var result = new MorphTargetManager(scene);
  94025. result._uniqueId = serializationObject.id;
  94026. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  94027. var targetData = _a[_i];
  94028. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  94029. }
  94030. return result;
  94031. };
  94032. return MorphTargetManager;
  94033. }());
  94034. BABYLON.MorphTargetManager = MorphTargetManager;
  94035. })(BABYLON || (BABYLON = {}));
  94036. //# sourceMappingURL=babylon.morphTargetManager.js.map
  94037. var BABYLON;
  94038. (function (BABYLON) {
  94039. var Octree = /** @class */ (function () {
  94040. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  94041. if (maxDepth === void 0) { maxDepth = 2; }
  94042. this.maxDepth = maxDepth;
  94043. this.dynamicContent = new Array();
  94044. this._maxBlockCapacity = maxBlockCapacity || 64;
  94045. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  94046. this._creationFunc = creationFunc;
  94047. }
  94048. // Methods
  94049. Octree.prototype.update = function (worldMin, worldMax, entries) {
  94050. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  94051. };
  94052. Octree.prototype.addMesh = function (entry) {
  94053. for (var index = 0; index < this.blocks.length; index++) {
  94054. var block = this.blocks[index];
  94055. block.addEntry(entry);
  94056. }
  94057. };
  94058. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  94059. this._selectionContent.reset();
  94060. for (var index = 0; index < this.blocks.length; index++) {
  94061. var block = this.blocks[index];
  94062. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  94063. }
  94064. if (allowDuplicate) {
  94065. this._selectionContent.concat(this.dynamicContent);
  94066. }
  94067. else {
  94068. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94069. }
  94070. return this._selectionContent;
  94071. };
  94072. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  94073. this._selectionContent.reset();
  94074. for (var index = 0; index < this.blocks.length; index++) {
  94075. var block = this.blocks[index];
  94076. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  94077. }
  94078. if (allowDuplicate) {
  94079. this._selectionContent.concat(this.dynamicContent);
  94080. }
  94081. else {
  94082. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94083. }
  94084. return this._selectionContent;
  94085. };
  94086. Octree.prototype.intersectsRay = function (ray) {
  94087. this._selectionContent.reset();
  94088. for (var index = 0; index < this.blocks.length; index++) {
  94089. var block = this.blocks[index];
  94090. block.intersectsRay(ray, this._selectionContent);
  94091. }
  94092. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  94093. return this._selectionContent;
  94094. };
  94095. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  94096. target.blocks = new Array();
  94097. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  94098. // Segmenting space
  94099. for (var x = 0; x < 2; x++) {
  94100. for (var y = 0; y < 2; y++) {
  94101. for (var z = 0; z < 2; z++) {
  94102. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  94103. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  94104. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  94105. block.addEntries(entries);
  94106. target.blocks.push(block);
  94107. }
  94108. }
  94109. }
  94110. };
  94111. Octree.CreationFuncForMeshes = function (entry, block) {
  94112. var boundingInfo = entry.getBoundingInfo();
  94113. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94114. block.entries.push(entry);
  94115. }
  94116. };
  94117. Octree.CreationFuncForSubMeshes = function (entry, block) {
  94118. var boundingInfo = entry.getBoundingInfo();
  94119. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  94120. block.entries.push(entry);
  94121. }
  94122. };
  94123. return Octree;
  94124. }());
  94125. BABYLON.Octree = Octree;
  94126. })(BABYLON || (BABYLON = {}));
  94127. //# sourceMappingURL=babylon.octree.js.map
  94128. var BABYLON;
  94129. (function (BABYLON) {
  94130. var OctreeBlock = /** @class */ (function () {
  94131. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  94132. this.entries = new Array();
  94133. this._boundingVectors = new Array();
  94134. this._capacity = capacity;
  94135. this._depth = depth;
  94136. this._maxDepth = maxDepth;
  94137. this._creationFunc = creationFunc;
  94138. this._minPoint = minPoint;
  94139. this._maxPoint = maxPoint;
  94140. this._boundingVectors.push(minPoint.clone());
  94141. this._boundingVectors.push(maxPoint.clone());
  94142. this._boundingVectors.push(minPoint.clone());
  94143. this._boundingVectors[2].x = maxPoint.x;
  94144. this._boundingVectors.push(minPoint.clone());
  94145. this._boundingVectors[3].y = maxPoint.y;
  94146. this._boundingVectors.push(minPoint.clone());
  94147. this._boundingVectors[4].z = maxPoint.z;
  94148. this._boundingVectors.push(maxPoint.clone());
  94149. this._boundingVectors[5].z = minPoint.z;
  94150. this._boundingVectors.push(maxPoint.clone());
  94151. this._boundingVectors[6].x = minPoint.x;
  94152. this._boundingVectors.push(maxPoint.clone());
  94153. this._boundingVectors[7].y = minPoint.y;
  94154. }
  94155. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  94156. // Property
  94157. get: function () {
  94158. return this._capacity;
  94159. },
  94160. enumerable: true,
  94161. configurable: true
  94162. });
  94163. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  94164. get: function () {
  94165. return this._minPoint;
  94166. },
  94167. enumerable: true,
  94168. configurable: true
  94169. });
  94170. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  94171. get: function () {
  94172. return this._maxPoint;
  94173. },
  94174. enumerable: true,
  94175. configurable: true
  94176. });
  94177. // Methods
  94178. OctreeBlock.prototype.addEntry = function (entry) {
  94179. if (this.blocks) {
  94180. for (var index = 0; index < this.blocks.length; index++) {
  94181. var block = this.blocks[index];
  94182. block.addEntry(entry);
  94183. }
  94184. return;
  94185. }
  94186. this._creationFunc(entry, this);
  94187. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  94188. this.createInnerBlocks();
  94189. }
  94190. };
  94191. OctreeBlock.prototype.addEntries = function (entries) {
  94192. for (var index = 0; index < entries.length; index++) {
  94193. var mesh = entries[index];
  94194. this.addEntry(mesh);
  94195. }
  94196. };
  94197. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  94198. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  94199. if (this.blocks) {
  94200. for (var index = 0; index < this.blocks.length; index++) {
  94201. var block = this.blocks[index];
  94202. block.select(frustumPlanes, selection, allowDuplicate);
  94203. }
  94204. return;
  94205. }
  94206. if (allowDuplicate) {
  94207. selection.concat(this.entries);
  94208. }
  94209. else {
  94210. selection.concatWithNoDuplicate(this.entries);
  94211. }
  94212. }
  94213. };
  94214. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  94215. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  94216. if (this.blocks) {
  94217. for (var index = 0; index < this.blocks.length; index++) {
  94218. var block = this.blocks[index];
  94219. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  94220. }
  94221. return;
  94222. }
  94223. if (allowDuplicate) {
  94224. selection.concat(this.entries);
  94225. }
  94226. else {
  94227. selection.concatWithNoDuplicate(this.entries);
  94228. }
  94229. }
  94230. };
  94231. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  94232. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  94233. if (this.blocks) {
  94234. for (var index = 0; index < this.blocks.length; index++) {
  94235. var block = this.blocks[index];
  94236. block.intersectsRay(ray, selection);
  94237. }
  94238. return;
  94239. }
  94240. selection.concatWithNoDuplicate(this.entries);
  94241. }
  94242. };
  94243. OctreeBlock.prototype.createInnerBlocks = function () {
  94244. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  94245. };
  94246. return OctreeBlock;
  94247. }());
  94248. BABYLON.OctreeBlock = OctreeBlock;
  94249. })(BABYLON || (BABYLON = {}));
  94250. //# sourceMappingURL=babylon.octreeBlock.js.map
  94251. var BABYLON;
  94252. (function (BABYLON) {
  94253. /**
  94254. * Postprocess used to generate anaglyphic rendering
  94255. */
  94256. var AnaglyphPostProcess = /** @class */ (function (_super) {
  94257. __extends(AnaglyphPostProcess, _super);
  94258. /**
  94259. * Creates a new AnaglyphPostProcess
  94260. * @param name defines postprocess name
  94261. * @param options defines creation options or target ratio scale
  94262. * @param rigCameras defines cameras using this postprocess
  94263. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  94264. * @param engine defines hosting engine
  94265. * @param reusable defines if the postprocess will be reused multiple times per frame
  94266. */
  94267. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  94268. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  94269. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94270. _this.onApplyObservable.add(function (effect) {
  94271. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  94272. });
  94273. return _this;
  94274. }
  94275. return AnaglyphPostProcess;
  94276. }(BABYLON.PostProcess));
  94277. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  94278. })(BABYLON || (BABYLON = {}));
  94279. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  94280. var BABYLON;
  94281. (function (BABYLON) {
  94282. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  94283. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94284. });
  94285. /**
  94286. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  94287. */
  94288. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  94289. __extends(AnaglyphArcRotateCamera, _super);
  94290. /**
  94291. * Creates a new AnaglyphArcRotateCamera
  94292. * @param name defines camera name
  94293. * @param alpha defines alpha angle (in radians)
  94294. * @param beta defines beta angle (in radians)
  94295. * @param radius defines radius
  94296. * @param target defines camera target
  94297. * @param interaxialDistance defines distance between each color axis
  94298. * @param scene defines the hosting scene
  94299. */
  94300. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  94301. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94302. _this.interaxialDistance = interaxialDistance;
  94303. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94304. return _this;
  94305. }
  94306. /**
  94307. * Gets camera class name
  94308. * @returns AnaglyphArcRotateCamera
  94309. */
  94310. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  94311. return "AnaglyphArcRotateCamera";
  94312. };
  94313. return AnaglyphArcRotateCamera;
  94314. }(BABYLON.ArcRotateCamera));
  94315. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  94316. })(BABYLON || (BABYLON = {}));
  94317. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  94318. var BABYLON;
  94319. (function (BABYLON) {
  94320. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  94321. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94322. });
  94323. /**
  94324. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  94325. */
  94326. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  94327. __extends(AnaglyphFreeCamera, _super);
  94328. /**
  94329. * Creates a new AnaglyphFreeCamera
  94330. * @param name defines camera name
  94331. * @param position defines initial position
  94332. * @param interaxialDistance defines distance between each color axis
  94333. * @param scene defines the hosting scene
  94334. */
  94335. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  94336. var _this = _super.call(this, name, position, scene) || this;
  94337. _this.interaxialDistance = interaxialDistance;
  94338. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94339. return _this;
  94340. }
  94341. /**
  94342. * Gets camera class name
  94343. * @returns AnaglyphFreeCamera
  94344. */
  94345. AnaglyphFreeCamera.prototype.getClassName = function () {
  94346. return "AnaglyphFreeCamera";
  94347. };
  94348. return AnaglyphFreeCamera;
  94349. }(BABYLON.FreeCamera));
  94350. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  94351. })(BABYLON || (BABYLON = {}));
  94352. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  94353. var BABYLON;
  94354. (function (BABYLON) {
  94355. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  94356. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94357. });
  94358. /**
  94359. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  94360. */
  94361. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  94362. __extends(AnaglyphGamepadCamera, _super);
  94363. /**
  94364. * Creates a new AnaglyphGamepadCamera
  94365. * @param name defines camera name
  94366. * @param position defines initial position
  94367. * @param interaxialDistance defines distance between each color axis
  94368. * @param scene defines the hosting scene
  94369. */
  94370. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  94371. var _this = _super.call(this, name, position, scene) || this;
  94372. _this.interaxialDistance = interaxialDistance;
  94373. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94374. return _this;
  94375. }
  94376. /**
  94377. * Gets camera class name
  94378. * @returns AnaglyphGamepadCamera
  94379. */
  94380. AnaglyphGamepadCamera.prototype.getClassName = function () {
  94381. return "AnaglyphGamepadCamera";
  94382. };
  94383. return AnaglyphGamepadCamera;
  94384. }(BABYLON.GamepadCamera));
  94385. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  94386. })(BABYLON || (BABYLON = {}));
  94387. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  94388. var BABYLON;
  94389. (function (BABYLON) {
  94390. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  94391. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  94392. });
  94393. /**
  94394. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  94395. */
  94396. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  94397. __extends(AnaglyphUniversalCamera, _super);
  94398. /**
  94399. * Creates a new AnaglyphUniversalCamera
  94400. * @param name defines camera name
  94401. * @param position defines initial position
  94402. * @param interaxialDistance defines distance between each color axis
  94403. * @param scene defines the hosting scene
  94404. */
  94405. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  94406. var _this = _super.call(this, name, position, scene) || this;
  94407. _this.interaxialDistance = interaxialDistance;
  94408. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  94409. return _this;
  94410. }
  94411. /**
  94412. * Gets camera class name
  94413. * @returns AnaglyphUniversalCamera
  94414. */
  94415. AnaglyphUniversalCamera.prototype.getClassName = function () {
  94416. return "AnaglyphUniversalCamera";
  94417. };
  94418. return AnaglyphUniversalCamera;
  94419. }(BABYLON.UniversalCamera));
  94420. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  94421. })(BABYLON || (BABYLON = {}));
  94422. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  94423. var BABYLON;
  94424. (function (BABYLON) {
  94425. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  94426. __extends(StereoscopicInterlacePostProcess, _super);
  94427. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  94428. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  94429. _this._passedProcess = rigCameras[0]._rigPostProcess;
  94430. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94431. _this.onSizeChangedObservable.add(function () {
  94432. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  94433. });
  94434. _this.onApplyObservable.add(function (effect) {
  94435. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  94436. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  94437. });
  94438. return _this;
  94439. }
  94440. return StereoscopicInterlacePostProcess;
  94441. }(BABYLON.PostProcess));
  94442. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  94443. })(BABYLON || (BABYLON = {}));
  94444. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  94445. var BABYLON;
  94446. (function (BABYLON) {
  94447. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  94448. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94449. });
  94450. /**
  94451. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  94452. */
  94453. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  94454. __extends(StereoscopicArcRotateCamera, _super);
  94455. /**
  94456. * Creates a new StereoscopicArcRotateCamera
  94457. * @param name defines camera name
  94458. * @param alpha defines alpha angle (in radians)
  94459. * @param beta defines beta angle (in radians)
  94460. * @param radius defines radius
  94461. * @param target defines camera target
  94462. * @param interaxialDistance defines distance between each color axis
  94463. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94464. * @param scene defines the hosting scene
  94465. */
  94466. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  94467. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94468. _this.interaxialDistance = interaxialDistance;
  94469. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94470. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94471. return _this;
  94472. }
  94473. /**
  94474. * Gets camera class name
  94475. * @returns StereoscopicArcRotateCamera
  94476. */
  94477. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  94478. return "StereoscopicArcRotateCamera";
  94479. };
  94480. return StereoscopicArcRotateCamera;
  94481. }(BABYLON.ArcRotateCamera));
  94482. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  94483. })(BABYLON || (BABYLON = {}));
  94484. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  94485. var BABYLON;
  94486. (function (BABYLON) {
  94487. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94488. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94489. });
  94490. /**
  94491. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  94492. */
  94493. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  94494. __extends(StereoscopicFreeCamera, _super);
  94495. /**
  94496. * Creates a new StereoscopicFreeCamera
  94497. * @param name defines camera name
  94498. * @param position defines initial position
  94499. * @param interaxialDistance defines distance between each color axis
  94500. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94501. * @param scene defines the hosting scene
  94502. */
  94503. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94504. var _this = _super.call(this, name, position, scene) || this;
  94505. _this.interaxialDistance = interaxialDistance;
  94506. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94507. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94508. return _this;
  94509. }
  94510. /**
  94511. * Gets camera class name
  94512. * @returns StereoscopicFreeCamera
  94513. */
  94514. StereoscopicFreeCamera.prototype.getClassName = function () {
  94515. return "StereoscopicFreeCamera";
  94516. };
  94517. return StereoscopicFreeCamera;
  94518. }(BABYLON.FreeCamera));
  94519. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  94520. })(BABYLON || (BABYLON = {}));
  94521. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  94522. var BABYLON;
  94523. (function (BABYLON) {
  94524. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  94525. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94526. });
  94527. /**
  94528. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  94529. */
  94530. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  94531. __extends(StereoscopicGamepadCamera, _super);
  94532. /**
  94533. * Creates a new StereoscopicGamepadCamera
  94534. * @param name defines camera name
  94535. * @param position defines initial position
  94536. * @param interaxialDistance defines distance between each color axis
  94537. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94538. * @param scene defines the hosting scene
  94539. */
  94540. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94541. var _this = _super.call(this, name, position, scene) || this;
  94542. _this.interaxialDistance = interaxialDistance;
  94543. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94544. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94545. return _this;
  94546. }
  94547. /**
  94548. * Gets camera class name
  94549. * @returns StereoscopicGamepadCamera
  94550. */
  94551. StereoscopicGamepadCamera.prototype.getClassName = function () {
  94552. return "StereoscopicGamepadCamera";
  94553. };
  94554. return StereoscopicGamepadCamera;
  94555. }(BABYLON.GamepadCamera));
  94556. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  94557. })(BABYLON || (BABYLON = {}));
  94558. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  94559. var BABYLON;
  94560. (function (BABYLON) {
  94561. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  94562. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  94563. });
  94564. /**
  94565. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  94566. */
  94567. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  94568. __extends(StereoscopicUniversalCamera, _super);
  94569. /**
  94570. * Creates a new StereoscopicUniversalCamera
  94571. * @param name defines camera name
  94572. * @param position defines initial position
  94573. * @param interaxialDistance defines distance between each color axis
  94574. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  94575. * @param scene defines the hosting scene
  94576. */
  94577. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  94578. var _this = _super.call(this, name, position, scene) || this;
  94579. _this.interaxialDistance = interaxialDistance;
  94580. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  94581. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  94582. return _this;
  94583. }
  94584. /**
  94585. * Gets camera class name
  94586. * @returns StereoscopicUniversalCamera
  94587. */
  94588. StereoscopicUniversalCamera.prototype.getClassName = function () {
  94589. return "StereoscopicUniversalCamera";
  94590. };
  94591. return StereoscopicUniversalCamera;
  94592. }(BABYLON.UniversalCamera));
  94593. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  94594. })(BABYLON || (BABYLON = {}));
  94595. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  94596. var BABYLON;
  94597. (function (BABYLON) {
  94598. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  94599. __extends(VRDistortionCorrectionPostProcess, _super);
  94600. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  94601. var _this = _super.call(this, name, "vrDistortionCorrection", [
  94602. 'LensCenter',
  94603. 'Scale',
  94604. 'ScaleIn',
  94605. 'HmdWarpParam'
  94606. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  94607. _this._isRightEye = isRightEye;
  94608. _this._distortionFactors = vrMetrics.distortionK;
  94609. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  94610. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  94611. _this.adaptScaleToCurrentViewport = true;
  94612. _this.onSizeChangedObservable.add(function () {
  94613. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  94614. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  94615. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  94616. });
  94617. _this.onApplyObservable.add(function (effect) {
  94618. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  94619. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  94620. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  94621. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  94622. });
  94623. return _this;
  94624. }
  94625. return VRDistortionCorrectionPostProcess;
  94626. }(BABYLON.PostProcess));
  94627. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  94628. })(BABYLON || (BABYLON = {}));
  94629. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  94630. var BABYLON;
  94631. (function (BABYLON) {
  94632. /**
  94633. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  94634. * Screen rotation is taken into account.
  94635. */
  94636. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  94637. function FreeCameraDeviceOrientationInput() {
  94638. var _this = this;
  94639. this._screenOrientationAngle = 0;
  94640. this._screenQuaternion = new BABYLON.Quaternion();
  94641. this._alpha = 0;
  94642. this._beta = 0;
  94643. this._gamma = 0;
  94644. this._orientationChanged = function () {
  94645. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  94646. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  94647. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  94648. };
  94649. this._deviceOrientation = function (evt) {
  94650. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  94651. _this._beta = evt.beta !== null ? evt.beta : 0;
  94652. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  94653. };
  94654. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  94655. this._orientationChanged();
  94656. }
  94657. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  94658. get: function () {
  94659. return this._camera;
  94660. },
  94661. set: function (camera) {
  94662. this._camera = camera;
  94663. if (this._camera != null && !this._camera.rotationQuaternion) {
  94664. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  94665. }
  94666. },
  94667. enumerable: true,
  94668. configurable: true
  94669. });
  94670. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94671. window.addEventListener("orientationchange", this._orientationChanged);
  94672. window.addEventListener("deviceorientation", this._deviceOrientation);
  94673. //In certain cases, the attach control is called AFTER orientation was changed,
  94674. //So this is needed.
  94675. this._orientationChanged();
  94676. };
  94677. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  94678. window.removeEventListener("orientationchange", this._orientationChanged);
  94679. window.removeEventListener("deviceorientation", this._deviceOrientation);
  94680. };
  94681. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  94682. //if no device orientation provided, don't update the rotation.
  94683. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  94684. if (!this._alpha)
  94685. return;
  94686. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  94687. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  94688. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  94689. //Mirror on XY Plane
  94690. this._camera.rotationQuaternion.z *= -1;
  94691. this._camera.rotationQuaternion.w *= -1;
  94692. };
  94693. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  94694. return "FreeCameraDeviceOrientationInput";
  94695. };
  94696. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  94697. return "deviceOrientation";
  94698. };
  94699. return FreeCameraDeviceOrientationInput;
  94700. }());
  94701. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  94702. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  94703. })(BABYLON || (BABYLON = {}));
  94704. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  94705. var BABYLON;
  94706. (function (BABYLON) {
  94707. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  94708. function ArcRotateCameraVRDeviceOrientationInput() {
  94709. this.alphaCorrection = 1;
  94710. this.betaCorrection = 1;
  94711. this.gammaCorrection = 1;
  94712. this._alpha = 0;
  94713. this._gamma = 0;
  94714. this._dirty = false;
  94715. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  94716. }
  94717. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  94718. this.camera.attachControl(element, noPreventDefault);
  94719. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  94720. };
  94721. /** @hidden */
  94722. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  94723. if (evt.alpha !== null) {
  94724. this._alpha = +evt.alpha | 0;
  94725. }
  94726. if (evt.gamma !== null) {
  94727. this._gamma = +evt.gamma | 0;
  94728. }
  94729. this._dirty = true;
  94730. };
  94731. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  94732. if (this._dirty) {
  94733. this._dirty = false;
  94734. if (this._gamma < 0) {
  94735. this._gamma = 180 + this._gamma;
  94736. }
  94737. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  94738. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  94739. }
  94740. };
  94741. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  94742. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  94743. };
  94744. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  94745. return "ArcRotateCameraVRDeviceOrientationInput";
  94746. };
  94747. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  94748. return "VRDeviceOrientation";
  94749. };
  94750. return ArcRotateCameraVRDeviceOrientationInput;
  94751. }());
  94752. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  94753. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  94754. })(BABYLON || (BABYLON = {}));
  94755. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  94756. var BABYLON;
  94757. (function (BABYLON) {
  94758. var VRCameraMetrics = /** @class */ (function () {
  94759. function VRCameraMetrics() {
  94760. this.compensateDistortion = true;
  94761. }
  94762. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  94763. get: function () {
  94764. return this.hResolution / (2 * this.vResolution);
  94765. },
  94766. enumerable: true,
  94767. configurable: true
  94768. });
  94769. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  94770. get: function () {
  94771. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  94772. },
  94773. enumerable: true,
  94774. configurable: true
  94775. });
  94776. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  94777. get: function () {
  94778. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94779. var h = (4 * meters) / this.hScreenSize;
  94780. return BABYLON.Matrix.Translation(h, 0, 0);
  94781. },
  94782. enumerable: true,
  94783. configurable: true
  94784. });
  94785. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  94786. get: function () {
  94787. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94788. var h = (4 * meters) / this.hScreenSize;
  94789. return BABYLON.Matrix.Translation(-h, 0, 0);
  94790. },
  94791. enumerable: true,
  94792. configurable: true
  94793. });
  94794. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  94795. get: function () {
  94796. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  94797. },
  94798. enumerable: true,
  94799. configurable: true
  94800. });
  94801. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  94802. get: function () {
  94803. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  94804. },
  94805. enumerable: true,
  94806. configurable: true
  94807. });
  94808. VRCameraMetrics.GetDefault = function () {
  94809. var result = new VRCameraMetrics();
  94810. result.hResolution = 1280;
  94811. result.vResolution = 800;
  94812. result.hScreenSize = 0.149759993;
  94813. result.vScreenSize = 0.0935999975;
  94814. result.vScreenCenter = 0.0467999987;
  94815. result.eyeToScreenDistance = 0.0410000011;
  94816. result.lensSeparationDistance = 0.0635000020;
  94817. result.interpupillaryDistance = 0.0640000030;
  94818. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  94819. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  94820. result.postProcessScaleFactor = 1.714605507808412;
  94821. result.lensCenterOffset = 0.151976421;
  94822. return result;
  94823. };
  94824. return VRCameraMetrics;
  94825. }());
  94826. BABYLON.VRCameraMetrics = VRCameraMetrics;
  94827. })(BABYLON || (BABYLON = {}));
  94828. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  94829. var BABYLON;
  94830. (function (BABYLON) {
  94831. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  94832. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94833. });
  94834. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  94835. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94836. });
  94837. /**
  94838. * This represents a WebVR camera.
  94839. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  94840. * @example http://doc.babylonjs.com/how_to/webvr_camera
  94841. */
  94842. var WebVRFreeCamera = /** @class */ (function (_super) {
  94843. __extends(WebVRFreeCamera, _super);
  94844. /**
  94845. * Instantiates a WebVRFreeCamera.
  94846. * @param name The name of the WebVRFreeCamera
  94847. * @param position The starting anchor position for the camera
  94848. * @param scene The scene the camera belongs to
  94849. * @param webVROptions a set of customizable options for the webVRCamera
  94850. */
  94851. function WebVRFreeCamera(name, position, scene, webVROptions) {
  94852. if (webVROptions === void 0) { webVROptions = {}; }
  94853. var _this = _super.call(this, name, position, scene) || this;
  94854. _this.webVROptions = webVROptions;
  94855. /**
  94856. * @hidden
  94857. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  94858. */
  94859. _this._vrDevice = null;
  94860. /**
  94861. * The rawPose of the vrDevice.
  94862. */
  94863. _this.rawPose = null;
  94864. _this._specsVersion = "1.1";
  94865. _this._attached = false;
  94866. _this._descendants = [];
  94867. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  94868. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  94869. /** @hidden */
  94870. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  94871. _this._standingMatrix = null;
  94872. /**
  94873. * Represents device position in babylon space.
  94874. */
  94875. _this.devicePosition = BABYLON.Vector3.Zero();
  94876. /**
  94877. * Represents device rotation in babylon space.
  94878. */
  94879. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  94880. /**
  94881. * The scale of the device to be used when translating from device space to babylon space.
  94882. */
  94883. _this.deviceScaleFactor = 1;
  94884. _this._deviceToWorld = BABYLON.Matrix.Identity();
  94885. _this._worldToDevice = BABYLON.Matrix.Identity();
  94886. /**
  94887. * References to the webVR controllers for the vrDevice.
  94888. */
  94889. _this.controllers = [];
  94890. /**
  94891. * Emits an event when a controller is attached.
  94892. */
  94893. _this.onControllersAttachedObservable = new BABYLON.Observable();
  94894. /**
  94895. * Emits an event when a controller's mesh has been loaded;
  94896. */
  94897. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94898. /**
  94899. * Emits an event when the HMD's pose has been updated.
  94900. */
  94901. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  94902. _this._poseSet = false;
  94903. /**
  94904. * If the rig cameras be used as parent instead of this camera.
  94905. */
  94906. _this.rigParenting = true;
  94907. _this._defaultHeight = undefined;
  94908. _this._htmlElementAttached = null;
  94909. _this._detachIfAttached = function () {
  94910. var vrDisplay = _this.getEngine().getVRDevice();
  94911. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  94912. _this.detachControl(_this._htmlElementAttached);
  94913. }
  94914. };
  94915. _this._workingVector = BABYLON.Vector3.Zero();
  94916. _this._oneVector = BABYLON.Vector3.One();
  94917. _this._workingMatrix = BABYLON.Matrix.Identity();
  94918. _this._cache.position = BABYLON.Vector3.Zero();
  94919. if (webVROptions.defaultHeight) {
  94920. _this._defaultHeight = webVROptions.defaultHeight;
  94921. _this.position.y = _this._defaultHeight;
  94922. }
  94923. _this.minZ = 0.1;
  94924. //legacy support - the compensation boolean was removed.
  94925. if (arguments.length === 5) {
  94926. _this.webVROptions = arguments[4];
  94927. }
  94928. // default webVR options
  94929. if (_this.webVROptions.trackPosition == undefined) {
  94930. _this.webVROptions.trackPosition = true;
  94931. }
  94932. if (_this.webVROptions.controllerMeshes == undefined) {
  94933. _this.webVROptions.controllerMeshes = true;
  94934. }
  94935. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  94936. _this.webVROptions.defaultLightingOnControllers = true;
  94937. }
  94938. _this.rotationQuaternion = new BABYLON.Quaternion();
  94939. if (_this.webVROptions && _this.webVROptions.positionScale) {
  94940. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  94941. }
  94942. //enable VR
  94943. var engine = _this.getEngine();
  94944. _this._onVREnabled = function (success) { if (success) {
  94945. _this.initControllers();
  94946. } };
  94947. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  94948. engine.initWebVR().add(function (event) {
  94949. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  94950. return;
  94951. }
  94952. _this._vrDevice = event.vrDisplay;
  94953. //reset the rig parameters.
  94954. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  94955. if (_this._attached) {
  94956. _this.getEngine().enableVR();
  94957. }
  94958. });
  94959. if (typeof (VRFrameData) !== "undefined")
  94960. _this._frameData = new VRFrameData();
  94961. /**
  94962. * The idea behind the following lines:
  94963. * objects that have the camera as parent should actually have the rig cameras as a parent.
  94964. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  94965. * the second will not show it correctly.
  94966. *
  94967. * To solve this - each object that has the camera as parent will be added to a protected array.
  94968. * When the rig camera renders, it will take this array and set all of those to be its children.
  94969. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  94970. * Amazing!
  94971. */
  94972. scene.onBeforeCameraRenderObservable.add(function (camera) {
  94973. if (camera.parent === _this && _this.rigParenting) {
  94974. _this._descendants = _this.getDescendants(true, function (n) {
  94975. // don't take the cameras or the controllers!
  94976. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  94977. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  94978. return !isController && !isRigCamera;
  94979. });
  94980. _this._descendants.forEach(function (node) {
  94981. node.parent = camera;
  94982. });
  94983. }
  94984. });
  94985. scene.onAfterCameraRenderObservable.add(function (camera) {
  94986. if (camera.parent === _this && _this.rigParenting) {
  94987. _this._descendants.forEach(function (node) {
  94988. node.parent = _this;
  94989. });
  94990. }
  94991. });
  94992. return _this;
  94993. }
  94994. /**
  94995. * Gets the device distance from the ground in meters.
  94996. * @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.
  94997. */
  94998. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  94999. if (this._standingMatrix) {
  95000. // Add standing matrix offset to get real offset from ground in room
  95001. this._standingMatrix.getTranslationToRef(this._workingVector);
  95002. return this._deviceRoomPosition.y + this._workingVector.y;
  95003. }
  95004. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  95005. return this._defaultHeight || 0;
  95006. };
  95007. /**
  95008. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95009. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  95010. */
  95011. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  95012. var _this = this;
  95013. if (callback === void 0) { callback = function (bool) { }; }
  95014. // Use standing matrix if available
  95015. this.getEngine().initWebVRAsync().then(function (result) {
  95016. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  95017. callback(false);
  95018. }
  95019. else {
  95020. _this._standingMatrix = new BABYLON.Matrix();
  95021. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  95022. if (!_this.getScene().useRightHandedSystem) {
  95023. [2, 6, 8, 9, 14].forEach(function (num) {
  95024. if (_this._standingMatrix) {
  95025. _this._standingMatrix.m[num] *= -1;
  95026. }
  95027. });
  95028. }
  95029. callback(true);
  95030. }
  95031. });
  95032. };
  95033. /**
  95034. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  95035. * @returns A promise with a boolean set to if the standing matrix is supported.
  95036. */
  95037. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  95038. var _this = this;
  95039. return new Promise(function (res, rej) {
  95040. _this.useStandingMatrix(function (supported) {
  95041. res(supported);
  95042. });
  95043. });
  95044. };
  95045. /**
  95046. * Disposes the camera
  95047. */
  95048. WebVRFreeCamera.prototype.dispose = function () {
  95049. this._detachIfAttached();
  95050. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  95051. _super.prototype.dispose.call(this);
  95052. };
  95053. /**
  95054. * Gets a vrController by name.
  95055. * @param name The name of the controller to retreive
  95056. * @returns the controller matching the name specified or null if not found
  95057. */
  95058. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  95059. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  95060. var gp = _a[_i];
  95061. if (gp.hand === name) {
  95062. return gp;
  95063. }
  95064. }
  95065. return null;
  95066. };
  95067. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  95068. /**
  95069. * The controller corrisponding to the users left hand.
  95070. */
  95071. get: function () {
  95072. if (!this._leftController) {
  95073. this._leftController = this.getControllerByName("left");
  95074. }
  95075. return this._leftController;
  95076. },
  95077. enumerable: true,
  95078. configurable: true
  95079. });
  95080. ;
  95081. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  95082. /**
  95083. * The controller corrisponding to the users right hand.
  95084. */
  95085. get: function () {
  95086. if (!this._rightController) {
  95087. this._rightController = this.getControllerByName("right");
  95088. }
  95089. return this._rightController;
  95090. },
  95091. enumerable: true,
  95092. configurable: true
  95093. });
  95094. ;
  95095. /**
  95096. * Casts a ray forward from the vrCamera's gaze.
  95097. * @param length Length of the ray (default: 100)
  95098. * @returns the ray corrisponding to the gaze
  95099. */
  95100. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  95101. if (length === void 0) { length = 100; }
  95102. if (this.leftCamera) {
  95103. // Use left eye to avoid computation to compute center on every call
  95104. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  95105. }
  95106. else {
  95107. return _super.prototype.getForwardRay.call(this, length);
  95108. }
  95109. };
  95110. /**
  95111. * @hidden
  95112. * Updates the camera based on device's frame data
  95113. */
  95114. WebVRFreeCamera.prototype._checkInputs = function () {
  95115. if (this._vrDevice && this._vrDevice.isPresenting) {
  95116. this._vrDevice.getFrameData(this._frameData);
  95117. this.updateFromDevice(this._frameData.pose);
  95118. }
  95119. _super.prototype._checkInputs.call(this);
  95120. };
  95121. /**
  95122. * Updates the poseControlled values based on the input device pose.
  95123. * @param poseData Pose coming from the device
  95124. */
  95125. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  95126. if (poseData && poseData.orientation) {
  95127. this.rawPose = poseData;
  95128. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  95129. if (this.getScene().useRightHandedSystem) {
  95130. this._deviceRoomRotationQuaternion.z *= -1;
  95131. this._deviceRoomRotationQuaternion.w *= -1;
  95132. }
  95133. if (this.webVROptions.trackPosition && this.rawPose.position) {
  95134. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  95135. if (this.getScene().useRightHandedSystem) {
  95136. this._deviceRoomPosition.z *= -1;
  95137. }
  95138. }
  95139. this._poseSet = true;
  95140. }
  95141. };
  95142. /**
  95143. * WebVR's attach control will start broadcasting frames to the device.
  95144. * Note that in certain browsers (chrome for example) this function must be called
  95145. * within a user-interaction callback. Example:
  95146. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  95147. *
  95148. * @param element html element to attach the vrDevice to
  95149. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  95150. */
  95151. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  95152. _super.prototype.attachControl.call(this, element, noPreventDefault);
  95153. this._attached = true;
  95154. this._htmlElementAttached = element;
  95155. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  95156. if (this._vrDevice) {
  95157. this.getEngine().enableVR();
  95158. }
  95159. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95160. };
  95161. /**
  95162. * Detaches the camera from the html element and disables VR
  95163. *
  95164. * @param element html element to detach from
  95165. */
  95166. WebVRFreeCamera.prototype.detachControl = function (element) {
  95167. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  95168. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  95169. _super.prototype.detachControl.call(this, element);
  95170. this._attached = false;
  95171. this.getEngine().disableVR();
  95172. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  95173. };
  95174. /**
  95175. * @returns the name of this class
  95176. */
  95177. WebVRFreeCamera.prototype.getClassName = function () {
  95178. return "WebVRFreeCamera";
  95179. };
  95180. /**
  95181. * Calls resetPose on the vrDisplay
  95182. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  95183. */
  95184. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  95185. //uses the vrDisplay's "resetPose()".
  95186. //pitch and roll won't be affected.
  95187. this._vrDevice.resetPose();
  95188. };
  95189. /**
  95190. * @hidden
  95191. * Updates the rig cameras (left and right eye)
  95192. */
  95193. WebVRFreeCamera.prototype._updateRigCameras = function () {
  95194. var camLeft = this._rigCameras[0];
  95195. var camRight = this._rigCameras[1];
  95196. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95197. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  95198. camLeft.position.copyFrom(this._deviceRoomPosition);
  95199. camRight.position.copyFrom(this._deviceRoomPosition);
  95200. };
  95201. /**
  95202. * @hidden
  95203. * Updates the cached values of the camera
  95204. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  95205. */
  95206. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  95207. var _this = this;
  95208. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  95209. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  95210. if (!this.updateCacheCalled) {
  95211. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  95212. this.updateCacheCalled = true;
  95213. this.update();
  95214. }
  95215. // Set working vector to the device position in room space rotated by the new rotation
  95216. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  95217. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  95218. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  95219. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  95220. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  95221. // Add translation from anchor position
  95222. this._deviceToWorld.getTranslationToRef(this._workingVector);
  95223. this._workingVector.addInPlace(this.position);
  95224. this._workingVector.subtractInPlace(this._cache.position);
  95225. this._deviceToWorld.setTranslation(this._workingVector);
  95226. // Set an inverted matrix to be used when updating the camera
  95227. this._deviceToWorld.invertToRef(this._worldToDevice);
  95228. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  95229. this.controllers.forEach(function (controller) {
  95230. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  95231. controller.update();
  95232. });
  95233. }
  95234. if (!ignoreParentClass) {
  95235. _super.prototype._updateCache.call(this);
  95236. }
  95237. this.updateCacheCalled = false;
  95238. };
  95239. /**
  95240. * Updates the current device position and rotation in the babylon world
  95241. */
  95242. WebVRFreeCamera.prototype.update = function () {
  95243. // Get current device position in babylon world
  95244. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  95245. // Get current device rotation in babylon world
  95246. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  95247. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  95248. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  95249. if (this._poseSet) {
  95250. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  95251. }
  95252. _super.prototype.update.call(this);
  95253. };
  95254. /**
  95255. * @hidden
  95256. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  95257. * @returns an identity matrix
  95258. */
  95259. WebVRFreeCamera.prototype._getViewMatrix = function () {
  95260. return BABYLON.Matrix.Identity();
  95261. };
  95262. /**
  95263. * This function is called by the two RIG cameras.
  95264. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  95265. */
  95266. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  95267. var _this = this;
  95268. // Update the parent camera prior to using a child camera to avoid desynchronization
  95269. var parentCamera = this._cameraRigParams["parentCamera"];
  95270. parentCamera._updateCache();
  95271. //WebVR 1.1
  95272. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  95273. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  95274. if (!this.getScene().useRightHandedSystem) {
  95275. [2, 6, 8, 9, 14].forEach(function (num) {
  95276. _this._webvrViewMatrix.m[num] *= -1;
  95277. });
  95278. }
  95279. // update the camera rotation matrix
  95280. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  95281. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  95282. // Computing target and final matrix
  95283. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  95284. // should the view matrix be updated with scale and position offset?
  95285. if (parentCamera.deviceScaleFactor !== 1) {
  95286. this._webvrViewMatrix.invert();
  95287. // scale the position, if set
  95288. if (parentCamera.deviceScaleFactor) {
  95289. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  95290. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  95291. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  95292. }
  95293. this._webvrViewMatrix.invert();
  95294. }
  95295. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  95296. // Compute global position
  95297. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  95298. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  95299. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  95300. this._workingMatrix.getTranslationToRef(this._globalPosition);
  95301. this._markSyncedWithParent();
  95302. return this._webvrViewMatrix;
  95303. };
  95304. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  95305. var _this = this;
  95306. var parentCamera = this.parent;
  95307. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  95308. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  95309. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  95310. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  95311. //babylon compatible matrix
  95312. if (!this.getScene().useRightHandedSystem) {
  95313. [8, 9, 10, 11].forEach(function (num) {
  95314. _this._projectionMatrix.m[num] *= -1;
  95315. });
  95316. }
  95317. return this._projectionMatrix;
  95318. };
  95319. /**
  95320. * Initializes the controllers and their meshes
  95321. */
  95322. WebVRFreeCamera.prototype.initControllers = function () {
  95323. var _this = this;
  95324. this.controllers = [];
  95325. var manager = this.getScene().gamepadManager;
  95326. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  95327. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95328. var webVrController = gamepad;
  95329. if (webVrController.defaultModel) {
  95330. webVrController.defaultModel.setEnabled(false);
  95331. }
  95332. if (webVrController.hand === "right") {
  95333. _this._rightController = null;
  95334. }
  95335. if (webVrController.hand === "left") {
  95336. _this._leftController = null;
  95337. }
  95338. var controllerIndex = _this.controllers.indexOf(webVrController);
  95339. if (controllerIndex !== -1) {
  95340. _this.controllers.splice(controllerIndex, 1);
  95341. }
  95342. }
  95343. });
  95344. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  95345. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  95346. var webVrController_1 = gamepad;
  95347. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  95348. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  95349. if (_this.webVROptions.controllerMeshes) {
  95350. if (webVrController_1.defaultModel) {
  95351. webVrController_1.defaultModel.setEnabled(true);
  95352. }
  95353. else {
  95354. // Load the meshes
  95355. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  95356. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  95357. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  95358. if (_this.webVROptions.defaultLightingOnControllers) {
  95359. if (!_this._lightOnControllers) {
  95360. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  95361. }
  95362. var activateLightOnSubMeshes_1 = function (mesh, light) {
  95363. var children = mesh.getChildren();
  95364. if (children.length !== 0) {
  95365. children.forEach(function (mesh) {
  95366. light.includedOnlyMeshes.push(mesh);
  95367. activateLightOnSubMeshes_1(mesh, light);
  95368. });
  95369. }
  95370. };
  95371. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  95372. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  95373. }
  95374. });
  95375. }
  95376. }
  95377. webVrController_1.attachToPoseControlledCamera(_this);
  95378. // since this is async - sanity check. Is the controller already stored?
  95379. if (_this.controllers.indexOf(webVrController_1) === -1) {
  95380. //add to the controllers array
  95381. _this.controllers.push(webVrController_1);
  95382. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  95383. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  95384. // So we're overriding setting left & right manually to be sure
  95385. var firstViveWandDetected = false;
  95386. for (var i = 0; i < _this.controllers.length; i++) {
  95387. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95388. if (!firstViveWandDetected) {
  95389. firstViveWandDetected = true;
  95390. _this.controllers[i].hand = "left";
  95391. }
  95392. else {
  95393. _this.controllers[i].hand = "right";
  95394. }
  95395. }
  95396. }
  95397. //did we find enough controllers? Great! let the developer know.
  95398. if (_this.controllers.length >= 2) {
  95399. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  95400. }
  95401. }
  95402. }
  95403. });
  95404. };
  95405. return WebVRFreeCamera;
  95406. }(BABYLON.FreeCamera));
  95407. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  95408. })(BABYLON || (BABYLON = {}));
  95409. //# sourceMappingURL=babylon.webVRCamera.js.map
  95410. var BABYLON;
  95411. (function (BABYLON) {
  95412. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  95413. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  95414. });
  95415. // We're mainly based on the logic defined into the FreeCamera code
  95416. /**
  95417. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  95418. * being tilted forward or back and left or right.
  95419. */
  95420. var DeviceOrientationCamera = /** @class */ (function (_super) {
  95421. __extends(DeviceOrientationCamera, _super);
  95422. /**
  95423. * Creates a new device orientation camera
  95424. * @param name The name of the camera
  95425. * @param position The start position camera
  95426. * @param scene The scene the camera belongs to
  95427. */
  95428. function DeviceOrientationCamera(name, position, scene) {
  95429. var _this = _super.call(this, name, position, scene) || this;
  95430. _this._quaternionCache = new BABYLON.Quaternion();
  95431. _this.inputs.addDeviceOrientation();
  95432. return _this;
  95433. }
  95434. /**
  95435. * Gets the current instance class name ("DeviceOrientationCamera").
  95436. * This helps avoiding instanceof at run time.
  95437. * @returns the class name
  95438. */
  95439. DeviceOrientationCamera.prototype.getClassName = function () {
  95440. return "DeviceOrientationCamera";
  95441. };
  95442. /**
  95443. * @hidden
  95444. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  95445. */
  95446. DeviceOrientationCamera.prototype._checkInputs = function () {
  95447. _super.prototype._checkInputs.call(this);
  95448. this._quaternionCache.copyFrom(this.rotationQuaternion);
  95449. if (this._initialQuaternion) {
  95450. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95451. }
  95452. };
  95453. /**
  95454. * Reset the camera to its default orientation on the specified axis only.
  95455. * @param axis The axis to reset
  95456. */
  95457. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  95458. var _this = this;
  95459. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  95460. //can only work if this camera has a rotation quaternion already.
  95461. if (!this.rotationQuaternion)
  95462. return;
  95463. if (!this._initialQuaternion) {
  95464. this._initialQuaternion = new BABYLON.Quaternion();
  95465. }
  95466. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  95467. ['x', 'y', 'z'].forEach(function (axisName) {
  95468. if (!axis[axisName]) {
  95469. _this._initialQuaternion[axisName] = 0;
  95470. }
  95471. else {
  95472. _this._initialQuaternion[axisName] *= -1;
  95473. }
  95474. });
  95475. this._initialQuaternion.normalize();
  95476. //force rotation update
  95477. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  95478. };
  95479. return DeviceOrientationCamera;
  95480. }(BABYLON.FreeCamera));
  95481. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  95482. })(BABYLON || (BABYLON = {}));
  95483. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  95484. var BABYLON;
  95485. (function (BABYLON) {
  95486. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95487. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  95488. });
  95489. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  95490. __extends(VRDeviceOrientationFreeCamera, _super);
  95491. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95492. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95493. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95494. var _this = _super.call(this, name, position, scene) || this;
  95495. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95496. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95497. return _this;
  95498. }
  95499. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  95500. return "VRDeviceOrientationFreeCamera";
  95501. };
  95502. return VRDeviceOrientationFreeCamera;
  95503. }(BABYLON.DeviceOrientationCamera));
  95504. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  95505. })(BABYLON || (BABYLON = {}));
  95506. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  95507. var BABYLON;
  95508. (function (BABYLON) {
  95509. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  95510. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  95511. });
  95512. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  95513. __extends(VRDeviceOrientationArcRotateCamera, _super);
  95514. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  95515. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95516. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95517. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95518. vrCameraMetrics.compensateDistortion = compensateDistortion;
  95519. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  95520. _this.inputs.addVRDeviceOrientation();
  95521. return _this;
  95522. }
  95523. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  95524. return "VRDeviceOrientationArcRotateCamera";
  95525. };
  95526. return VRDeviceOrientationArcRotateCamera;
  95527. }(BABYLON.ArcRotateCamera));
  95528. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  95529. })(BABYLON || (BABYLON = {}));
  95530. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  95531. var BABYLON;
  95532. (function (BABYLON) {
  95533. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  95534. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  95535. });
  95536. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  95537. __extends(VRDeviceOrientationGamepadCamera, _super);
  95538. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  95539. if (compensateDistortion === void 0) { compensateDistortion = true; }
  95540. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  95541. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  95542. _this.inputs.addGamepad();
  95543. return _this;
  95544. }
  95545. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  95546. return "VRDeviceOrientationGamepadCamera";
  95547. };
  95548. return VRDeviceOrientationGamepadCamera;
  95549. }(BABYLON.VRDeviceOrientationFreeCamera));
  95550. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  95551. })(BABYLON || (BABYLON = {}));
  95552. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  95553. var BABYLON;
  95554. (function (BABYLON) {
  95555. var VRExperienceHelperGazer = /** @class */ (function () {
  95556. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  95557. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  95558. this.scene = scene;
  95559. /** @hidden */
  95560. this._pointerDownOnMeshAsked = false;
  95561. /** @hidden */
  95562. this._isActionableMesh = false;
  95563. /** @hidden */
  95564. this._teleportationRequestInitiated = false;
  95565. /** @hidden */
  95566. this._teleportationBackRequestInitiated = false;
  95567. /** @hidden */
  95568. this._rotationRightAsked = false;
  95569. /** @hidden */
  95570. this._rotationLeftAsked = false;
  95571. /** @hidden */
  95572. this._dpadPressed = true;
  95573. /** @hidden */
  95574. this._activePointer = false;
  95575. this._id = VRExperienceHelperGazer._idCounter++;
  95576. // Gaze tracker
  95577. if (!gazeTrackerToClone) {
  95578. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  95579. this._gazeTracker.bakeCurrentTransformIntoVertices();
  95580. this._gazeTracker.isPickable = false;
  95581. this._gazeTracker.isVisible = false;
  95582. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  95583. targetMat.specularColor = BABYLON.Color3.Black();
  95584. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95585. targetMat.backFaceCulling = false;
  95586. this._gazeTracker.material = targetMat;
  95587. }
  95588. else {
  95589. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  95590. }
  95591. }
  95592. /** @hidden */
  95593. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  95594. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  95595. };
  95596. /** @hidden */
  95597. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  95598. this._pointerDownOnMeshAsked = true;
  95599. if (this._currentHit) {
  95600. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  95601. }
  95602. };
  95603. /** @hidden */
  95604. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  95605. if (this._currentHit) {
  95606. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  95607. }
  95608. this._pointerDownOnMeshAsked = false;
  95609. };
  95610. /** @hidden */
  95611. VRExperienceHelperGazer.prototype._activatePointer = function () {
  95612. this._activePointer = true;
  95613. };
  95614. /** @hidden */
  95615. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  95616. this._activePointer = false;
  95617. };
  95618. /** @hidden */
  95619. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  95620. if (distance === void 0) { distance = 100; }
  95621. };
  95622. VRExperienceHelperGazer.prototype.dispose = function () {
  95623. this._interactionsEnabled = false;
  95624. this._teleportationEnabled = false;
  95625. if (this._gazeTracker) {
  95626. this._gazeTracker.dispose();
  95627. }
  95628. };
  95629. VRExperienceHelperGazer._idCounter = 0;
  95630. return VRExperienceHelperGazer;
  95631. }());
  95632. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  95633. __extends(VRExperienceHelperControllerGazer, _super);
  95634. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  95635. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  95636. _this.webVRController = webVRController;
  95637. // Laser pointer
  95638. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  95639. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  95640. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  95641. laserPointerMaterial.alpha = 0.6;
  95642. _this._laserPointer.material = laserPointerMaterial;
  95643. _this._laserPointer.rotation.x = Math.PI / 2;
  95644. _this._laserPointer.position.z = -0.5;
  95645. _this._laserPointer.isVisible = false;
  95646. _this._laserPointer.isPickable = false;
  95647. if (!webVRController.mesh) {
  95648. // Create an empty mesh that is used prior to loading the high quality model
  95649. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  95650. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  95651. preloadPointerPose.rotation.x = -0.7;
  95652. preloadMesh.addChild(preloadPointerPose);
  95653. webVRController.attachToMesh(preloadMesh);
  95654. }
  95655. _this._setLaserPointerParent(webVRController.mesh);
  95656. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  95657. _this._setLaserPointerParent(mesh);
  95658. });
  95659. return _this;
  95660. }
  95661. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  95662. return this.webVRController.getForwardRay(length);
  95663. };
  95664. /** @hidden */
  95665. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  95666. _super.prototype._activatePointer.call(this);
  95667. this._laserPointer.isVisible = true;
  95668. };
  95669. /** @hidden */
  95670. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  95671. _super.prototype._deactivatePointer.call(this);
  95672. this._laserPointer.isVisible = false;
  95673. };
  95674. /** @hidden */
  95675. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  95676. this._laserPointer.material.emissiveColor = color;
  95677. };
  95678. /** @hidden */
  95679. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  95680. var makeNotPick = function (root) {
  95681. root.isPickable = false;
  95682. root.getChildMeshes().forEach(function (c) {
  95683. makeNotPick(c);
  95684. });
  95685. };
  95686. makeNotPick(mesh);
  95687. var childMeshes = mesh.getChildMeshes();
  95688. this.webVRController._pointingPoseNode = null;
  95689. for (var i = 0; i < childMeshes.length; i++) {
  95690. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  95691. mesh = childMeshes[i];
  95692. this.webVRController._pointingPoseNode = mesh;
  95693. break;
  95694. }
  95695. }
  95696. this._laserPointer.parent = mesh;
  95697. };
  95698. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  95699. if (distance === void 0) { distance = 100; }
  95700. this._laserPointer.scaling.y = distance;
  95701. this._laserPointer.position.z = -distance / 2;
  95702. };
  95703. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  95704. _super.prototype.dispose.call(this);
  95705. this._laserPointer.dispose();
  95706. if (this._meshAttachedObserver) {
  95707. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  95708. }
  95709. };
  95710. return VRExperienceHelperControllerGazer;
  95711. }(VRExperienceHelperGazer));
  95712. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  95713. __extends(VRExperienceHelperCameraGazer, _super);
  95714. function VRExperienceHelperCameraGazer(getCamera, scene) {
  95715. var _this = _super.call(this, scene) || this;
  95716. _this.getCamera = getCamera;
  95717. return _this;
  95718. }
  95719. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  95720. var camera = this.getCamera();
  95721. if (camera) {
  95722. return camera.getForwardRay(length);
  95723. }
  95724. else {
  95725. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  95726. }
  95727. };
  95728. return VRExperienceHelperCameraGazer;
  95729. }(VRExperienceHelperGazer));
  95730. /**
  95731. * Helps to quickly add VR support to an existing scene.
  95732. * See http://doc.babylonjs.com/how_to/webvr_helper
  95733. */
  95734. var VRExperienceHelper = /** @class */ (function () {
  95735. /**
  95736. * Instantiates a VRExperienceHelper.
  95737. * Helps to quickly add VR support to an existing scene.
  95738. * @param scene The scene the VRExperienceHelper belongs to.
  95739. * @param webVROptions Options to modify the vr experience helper's behavior.
  95740. */
  95741. function VRExperienceHelper(scene,
  95742. /** Options to modify the vr experience helper's behavior. */
  95743. webVROptions) {
  95744. if (webVROptions === void 0) { webVROptions = {}; }
  95745. var _this = this;
  95746. this.webVROptions = webVROptions;
  95747. // Can the system support WebVR, even if a headset isn't plugged in?
  95748. this._webVRsupported = false;
  95749. // If WebVR is supported, is a headset plugged in and are we ready to present?
  95750. this._webVRready = false;
  95751. // Are we waiting for the requestPresent callback to complete?
  95752. this._webVRrequesting = false;
  95753. // Are we presenting to the headset right now? (this is the vrDevice state)
  95754. this._webVRpresenting = false;
  95755. // Are we presenting in the fullscreen fallback?
  95756. this._fullscreenVRpresenting = false;
  95757. /**
  95758. * Observable raised when entering VR.
  95759. */
  95760. this.onEnteringVRObservable = new BABYLON.Observable();
  95761. /**
  95762. * Observable raised when exiting VR.
  95763. */
  95764. this.onExitingVRObservable = new BABYLON.Observable();
  95765. /**
  95766. * Observable raised when controller mesh is loaded.
  95767. */
  95768. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95769. this._useCustomVRButton = false;
  95770. this._teleportationRequested = false;
  95771. this._teleportActive = false;
  95772. this._floorMeshesCollection = [];
  95773. this._rotationAllowed = true;
  95774. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  95775. this._isDefaultTeleportationTarget = true;
  95776. this._teleportationFillColor = "#444444";
  95777. this._teleportationBorderColor = "#FFFFFF";
  95778. this._rotationAngle = 0;
  95779. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  95780. this._padSensibilityUp = 0.65;
  95781. this._padSensibilityDown = 0.35;
  95782. this._leftController = null;
  95783. this._rightController = null;
  95784. /**
  95785. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  95786. */
  95787. this.onNewMeshSelected = new BABYLON.Observable();
  95788. /**
  95789. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  95790. */
  95791. this.onNewMeshPicked = new BABYLON.Observable();
  95792. /**
  95793. * Observable raised before camera teleportation
  95794. */
  95795. this.onBeforeCameraTeleport = new BABYLON.Observable();
  95796. /**
  95797. * Observable raised after camera teleportation
  95798. */
  95799. this.onAfterCameraTeleport = new BABYLON.Observable();
  95800. /**
  95801. * Observable raised when current selected mesh gets unselected
  95802. */
  95803. this.onSelectedMeshUnselected = new BABYLON.Observable();
  95804. /**
  95805. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  95806. */
  95807. this.teleportationEnabled = true;
  95808. this._teleportationInitialized = false;
  95809. this._interactionsEnabled = false;
  95810. this._interactionsRequested = false;
  95811. this._displayGaze = true;
  95812. this._displayLaserPointer = true;
  95813. /**
  95814. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  95815. */
  95816. this.updateGazeTrackerScale = true;
  95817. this._onResize = function () {
  95818. _this.moveButtonToBottomRight();
  95819. if (_this._fullscreenVRpresenting && _this._webVRready) {
  95820. _this.exitVR();
  95821. }
  95822. };
  95823. this._onFullscreenChange = function () {
  95824. if (document.fullscreen !== undefined) {
  95825. _this._fullscreenVRpresenting = document.fullscreen;
  95826. }
  95827. else if (document.mozFullScreen !== undefined) {
  95828. _this._fullscreenVRpresenting = document.mozFullScreen;
  95829. }
  95830. else if (document.webkitIsFullScreen !== undefined) {
  95831. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  95832. }
  95833. else if (document.msIsFullScreen !== undefined) {
  95834. _this._fullscreenVRpresenting = document.msIsFullScreen;
  95835. }
  95836. else if (document.msFullscreenElement !== undefined) {
  95837. _this._fullscreenVRpresenting = document.msFullscreenElement;
  95838. }
  95839. if (!_this._fullscreenVRpresenting && _this._canvas) {
  95840. _this.exitVR();
  95841. if (!_this._useCustomVRButton) {
  95842. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  95843. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  95844. }
  95845. }
  95846. };
  95847. this.beforeRender = function () {
  95848. if (_this._leftController && _this._leftController._activePointer) {
  95849. _this._castRayAndSelectObject(_this._leftController);
  95850. }
  95851. if (_this._rightController && _this._rightController._activePointer) {
  95852. _this._castRayAndSelectObject(_this._rightController);
  95853. }
  95854. if (_this._noControllerIsActive) {
  95855. _this._castRayAndSelectObject(_this._cameraGazer);
  95856. }
  95857. else {
  95858. _this._cameraGazer._gazeTracker.isVisible = false;
  95859. }
  95860. };
  95861. this._onNewGamepadConnected = function (gamepad) {
  95862. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  95863. if (gamepad.leftStick) {
  95864. gamepad.onleftstickchanged(function (stickValues) {
  95865. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  95866. // Listening to classic/xbox gamepad only if no VR controller is active
  95867. if ((!_this._leftController && !_this._rightController) ||
  95868. ((_this._leftController && !_this._leftController._activePointer) &&
  95869. (_this._rightController && !_this._rightController._activePointer))) {
  95870. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  95871. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  95872. }
  95873. }
  95874. });
  95875. }
  95876. if (gamepad.rightStick) {
  95877. gamepad.onrightstickchanged(function (stickValues) {
  95878. if (_this._teleportationInitialized) {
  95879. _this._checkRotate(stickValues, _this._cameraGazer);
  95880. }
  95881. });
  95882. }
  95883. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  95884. gamepad.onbuttondown(function (buttonPressed) {
  95885. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95886. _this._cameraGazer._selectionPointerDown();
  95887. }
  95888. });
  95889. gamepad.onbuttonup(function (buttonPressed) {
  95890. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95891. _this._cameraGazer._selectionPointerUp();
  95892. }
  95893. });
  95894. }
  95895. }
  95896. else {
  95897. var webVRController = gamepad;
  95898. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  95899. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  95900. _this._rightController = controller;
  95901. }
  95902. else {
  95903. _this._leftController = controller;
  95904. }
  95905. _this._tryEnableInteractionOnController(controller);
  95906. }
  95907. };
  95908. // 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
  95909. this._tryEnableInteractionOnController = function (controller) {
  95910. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  95911. _this._enableInteractionOnController(controller);
  95912. }
  95913. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  95914. _this._enableTeleportationOnController(controller);
  95915. }
  95916. };
  95917. this._onNewGamepadDisconnected = function (gamepad) {
  95918. if (gamepad instanceof BABYLON.WebVRController) {
  95919. if (gamepad.hand === "left" && _this._leftController != null) {
  95920. _this._leftController.dispose();
  95921. _this._leftController = null;
  95922. }
  95923. if (gamepad.hand === "right" && _this._rightController != null) {
  95924. _this._rightController.dispose();
  95925. _this._rightController = null;
  95926. }
  95927. }
  95928. };
  95929. this._workingVector = BABYLON.Vector3.Zero();
  95930. this._workingQuaternion = BABYLON.Quaternion.Identity();
  95931. this._workingMatrix = BABYLON.Matrix.Identity();
  95932. this._scene = scene;
  95933. this._canvas = scene.getEngine().getRenderingCanvas();
  95934. // Parse options
  95935. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  95936. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  95937. }
  95938. if (webVROptions.createDeviceOrientationCamera === undefined) {
  95939. webVROptions.createDeviceOrientationCamera = true;
  95940. }
  95941. if (webVROptions.laserToggle === undefined) {
  95942. webVROptions.laserToggle = true;
  95943. }
  95944. if (webVROptions.defaultHeight === undefined) {
  95945. webVROptions.defaultHeight = 1.7;
  95946. }
  95947. if (webVROptions.useCustomVRButton) {
  95948. this._useCustomVRButton = true;
  95949. if (webVROptions.customVRButton) {
  95950. this._btnVR = webVROptions.customVRButton;
  95951. }
  95952. }
  95953. if (webVROptions.rayLength) {
  95954. this._rayLength = webVROptions.rayLength;
  95955. }
  95956. this._defaultHeight = webVROptions.defaultHeight;
  95957. if (webVROptions.positionScale) {
  95958. this._rayLength *= webVROptions.positionScale;
  95959. this._defaultHeight *= webVROptions.positionScale;
  95960. }
  95961. this._hasEnteredVR = false;
  95962. // Set position
  95963. if (this._scene.activeCamera) {
  95964. this._position = this._scene.activeCamera.position.clone();
  95965. }
  95966. else {
  95967. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  95968. }
  95969. // Set non-vr camera
  95970. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  95971. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  95972. // Copy data from existing camera
  95973. if (this._scene.activeCamera) {
  95974. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95975. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  95976. // Set rotation from previous camera
  95977. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  95978. var targetCamera = this._scene.activeCamera;
  95979. if (targetCamera.rotationQuaternion) {
  95980. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  95981. }
  95982. else {
  95983. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  95984. }
  95985. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  95986. }
  95987. }
  95988. this._scene.activeCamera = this._deviceOrientationCamera;
  95989. if (this._canvas) {
  95990. this._scene.activeCamera.attachControl(this._canvas);
  95991. }
  95992. }
  95993. else {
  95994. this._existingCamera = this._scene.activeCamera;
  95995. }
  95996. // Create VR cameras
  95997. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95998. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  95999. }
  96000. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  96001. this._webVRCamera.useStandingMatrix();
  96002. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  96003. // Create default button
  96004. if (!this._useCustomVRButton) {
  96005. this._btnVR = document.createElement("BUTTON");
  96006. this._btnVR.className = "babylonVRicon";
  96007. this._btnVR.id = "babylonVRiconbtn";
  96008. this._btnVR.title = "Click to switch to VR";
  96009. 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) }";
  96010. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  96011. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  96012. // css += ".babylonVRicon.vrdisplaysupported { }";
  96013. // css += ".babylonVRicon.vrdisplayready { }";
  96014. // css += ".babylonVRicon.vrdisplayrequesting { }";
  96015. var style = document.createElement('style');
  96016. style.appendChild(document.createTextNode(css));
  96017. document.getElementsByTagName('head')[0].appendChild(style);
  96018. this.moveButtonToBottomRight();
  96019. }
  96020. // VR button click event
  96021. if (this._btnVR) {
  96022. this._btnVR.addEventListener("click", function () {
  96023. if (!_this.isInVRMode) {
  96024. _this.enterVR();
  96025. }
  96026. else {
  96027. _this.exitVR();
  96028. }
  96029. });
  96030. }
  96031. // Window events
  96032. window.addEventListener("resize", this._onResize);
  96033. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  96034. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  96035. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  96036. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  96037. document.onmsfullscreenchange = this._onFullscreenChange;
  96038. // Display vr button when headset is connected
  96039. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  96040. this.displayVRButton();
  96041. }
  96042. else {
  96043. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  96044. if (e.vrDisplay) {
  96045. _this.displayVRButton();
  96046. }
  96047. });
  96048. }
  96049. // Exiting VR mode using 'ESC' key on desktop
  96050. this._onKeyDown = function (event) {
  96051. if (event.keyCode === 27 && _this.isInVRMode) {
  96052. _this.exitVR();
  96053. }
  96054. };
  96055. document.addEventListener("keydown", this._onKeyDown);
  96056. // Exiting VR mode double tapping the touch screen
  96057. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  96058. if (_this.isInVRMode) {
  96059. _this.exitVR();
  96060. if (_this._fullscreenVRpresenting) {
  96061. _this._scene.getEngine().switchFullscreen(true);
  96062. }
  96063. }
  96064. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  96065. // Listen for WebVR display changes
  96066. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  96067. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  96068. this._onVRRequestPresentStart = function () {
  96069. _this._webVRrequesting = true;
  96070. _this.updateButtonVisibility();
  96071. };
  96072. this._onVRRequestPresentComplete = function (success) {
  96073. _this._webVRrequesting = false;
  96074. _this.updateButtonVisibility();
  96075. };
  96076. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  96077. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  96078. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  96079. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96080. scene.onDisposeObservable.add(function () {
  96081. _this.dispose();
  96082. });
  96083. // Gamepad connection events
  96084. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  96085. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  96086. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  96087. this.updateButtonVisibility();
  96088. //create easing functions
  96089. this._circleEase = new BABYLON.CircleEase();
  96090. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96091. if (this.webVROptions.floorMeshes) {
  96092. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  96093. }
  96094. }
  96095. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  96096. /** Return this.onEnteringVRObservable
  96097. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  96098. */
  96099. get: function () {
  96100. return this.onEnteringVRObservable;
  96101. },
  96102. enumerable: true,
  96103. configurable: true
  96104. });
  96105. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  96106. /** Return this.onExitingVRObservable
  96107. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  96108. */
  96109. get: function () {
  96110. return this.onExitingVRObservable;
  96111. },
  96112. enumerable: true,
  96113. configurable: true
  96114. });
  96115. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  96116. /** Return this.onControllerMeshLoadedObservable
  96117. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  96118. */
  96119. get: function () {
  96120. return this.onControllerMeshLoadedObservable;
  96121. },
  96122. enumerable: true,
  96123. configurable: true
  96124. });
  96125. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  96126. /**
  96127. * The mesh used to display where the user is going to teleport.
  96128. */
  96129. get: function () {
  96130. return this._teleportationTarget;
  96131. },
  96132. /**
  96133. * Sets the mesh to be used to display where the user is going to teleport.
  96134. */
  96135. set: function (value) {
  96136. if (value) {
  96137. value.name = "teleportationTarget";
  96138. this._isDefaultTeleportationTarget = false;
  96139. this._teleportationTarget = value;
  96140. }
  96141. },
  96142. enumerable: true,
  96143. configurable: true
  96144. });
  96145. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  96146. /**
  96147. * 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
  96148. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  96149. * See http://doc.babylonjs.com/resources/baking_transformations
  96150. */
  96151. get: function () {
  96152. return this._cameraGazer._gazeTracker;
  96153. },
  96154. set: function (value) {
  96155. if (value) {
  96156. // Dispose of existing meshes
  96157. if (this._cameraGazer._gazeTracker) {
  96158. this._cameraGazer._gazeTracker.dispose();
  96159. }
  96160. if (this._leftController && this._leftController._gazeTracker) {
  96161. this._leftController._gazeTracker.dispose();
  96162. }
  96163. if (this._rightController && this._rightController._gazeTracker) {
  96164. this._rightController._gazeTracker.dispose();
  96165. }
  96166. // Set and create gaze trackers on head and controllers
  96167. this._cameraGazer._gazeTracker = value;
  96168. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  96169. this._cameraGazer._gazeTracker.isPickable = false;
  96170. this._cameraGazer._gazeTracker.isVisible = false;
  96171. this._cameraGazer._gazeTracker.name = "gazeTracker";
  96172. if (this._leftController) {
  96173. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96174. }
  96175. if (this._rightController) {
  96176. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  96177. }
  96178. }
  96179. },
  96180. enumerable: true,
  96181. configurable: true
  96182. });
  96183. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  96184. /**
  96185. * The gaze tracking mesh corresponding to the left controller
  96186. */
  96187. get: function () {
  96188. if (this._leftController) {
  96189. return this._leftController._gazeTracker;
  96190. }
  96191. return null;
  96192. },
  96193. enumerable: true,
  96194. configurable: true
  96195. });
  96196. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  96197. /**
  96198. * The gaze tracking mesh corresponding to the right controller
  96199. */
  96200. get: function () {
  96201. if (this._rightController) {
  96202. return this._rightController._gazeTracker;
  96203. }
  96204. return null;
  96205. },
  96206. enumerable: true,
  96207. configurable: true
  96208. });
  96209. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  96210. /**
  96211. * If the ray of the gaze should be displayed.
  96212. */
  96213. get: function () {
  96214. return this._displayGaze;
  96215. },
  96216. /**
  96217. * Sets if the ray of the gaze should be displayed.
  96218. */
  96219. set: function (value) {
  96220. this._displayGaze = value;
  96221. if (!value) {
  96222. this._cameraGazer._gazeTracker.isVisible = false;
  96223. if (this._leftController) {
  96224. this._leftController._gazeTracker.isVisible = false;
  96225. }
  96226. if (this._rightController) {
  96227. this._rightController._gazeTracker.isVisible = false;
  96228. }
  96229. }
  96230. },
  96231. enumerable: true,
  96232. configurable: true
  96233. });
  96234. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  96235. /**
  96236. * If the ray of the LaserPointer should be displayed.
  96237. */
  96238. get: function () {
  96239. return this._displayLaserPointer;
  96240. },
  96241. /**
  96242. * Sets if the ray of the LaserPointer should be displayed.
  96243. */
  96244. set: function (value) {
  96245. this._displayLaserPointer = value;
  96246. if (!value) {
  96247. if (this._rightController) {
  96248. this._rightController._deactivatePointer();
  96249. this._rightController._gazeTracker.isVisible = false;
  96250. }
  96251. if (this._leftController) {
  96252. this._leftController._deactivatePointer();
  96253. this._leftController._gazeTracker.isVisible = false;
  96254. }
  96255. }
  96256. else {
  96257. if (this._rightController) {
  96258. this._rightController._activatePointer();
  96259. }
  96260. if (this._leftController) {
  96261. this._leftController._activatePointer();
  96262. }
  96263. }
  96264. },
  96265. enumerable: true,
  96266. configurable: true
  96267. });
  96268. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  96269. /**
  96270. * The deviceOrientationCamera used as the camera when not in VR.
  96271. */
  96272. get: function () {
  96273. return this._deviceOrientationCamera;
  96274. },
  96275. enumerable: true,
  96276. configurable: true
  96277. });
  96278. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  96279. /**
  96280. * Based on the current WebVR support, returns the current VR camera used.
  96281. */
  96282. get: function () {
  96283. if (this._webVRready) {
  96284. return this._webVRCamera;
  96285. }
  96286. else {
  96287. return this._scene.activeCamera;
  96288. }
  96289. },
  96290. enumerable: true,
  96291. configurable: true
  96292. });
  96293. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  96294. /**
  96295. * The webVRCamera which is used when in VR.
  96296. */
  96297. get: function () {
  96298. return this._webVRCamera;
  96299. },
  96300. enumerable: true,
  96301. configurable: true
  96302. });
  96303. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  96304. /**
  96305. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  96306. */
  96307. get: function () {
  96308. return this._vrDeviceOrientationCamera;
  96309. },
  96310. enumerable: true,
  96311. configurable: true
  96312. });
  96313. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  96314. get: function () {
  96315. var result = this._cameraGazer._teleportationRequestInitiated
  96316. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  96317. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  96318. return result;
  96319. },
  96320. enumerable: true,
  96321. configurable: true
  96322. });
  96323. // Raised when one of the controller has loaded successfully its associated default mesh
  96324. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  96325. if (this._leftController && this._leftController.webVRController == webVRController) {
  96326. if (webVRController.mesh) {
  96327. this._leftController._setLaserPointerParent(webVRController.mesh);
  96328. }
  96329. }
  96330. if (this._rightController && this._rightController.webVRController == webVRController) {
  96331. if (webVRController.mesh) {
  96332. this._rightController._setLaserPointerParent(webVRController.mesh);
  96333. }
  96334. }
  96335. try {
  96336. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  96337. }
  96338. catch (err) {
  96339. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  96340. }
  96341. };
  96342. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  96343. /**
  96344. * Gets a value indicating if we are currently in VR mode.
  96345. */
  96346. get: function () {
  96347. return this._webVRpresenting || this._fullscreenVRpresenting;
  96348. },
  96349. enumerable: true,
  96350. configurable: true
  96351. });
  96352. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  96353. var vrDisplay = this._scene.getEngine().getVRDevice();
  96354. if (vrDisplay) {
  96355. var wasPresenting = this._webVRpresenting;
  96356. this._webVRpresenting = vrDisplay.isPresenting;
  96357. if (wasPresenting && !this._webVRpresenting)
  96358. this.exitVR();
  96359. }
  96360. else {
  96361. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  96362. }
  96363. this.updateButtonVisibility();
  96364. };
  96365. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  96366. this._webVRsupported = eventArgs.vrSupported;
  96367. this._webVRready = !!eventArgs.vrDisplay;
  96368. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  96369. this.updateButtonVisibility();
  96370. };
  96371. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  96372. if (this._canvas && !this._useCustomVRButton) {
  96373. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  96374. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  96375. }
  96376. };
  96377. VRExperienceHelper.prototype.displayVRButton = function () {
  96378. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  96379. document.body.appendChild(this._btnVR);
  96380. this._btnVRDisplayed = true;
  96381. }
  96382. };
  96383. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  96384. if (!this._btnVR || this._useCustomVRButton) {
  96385. return;
  96386. }
  96387. this._btnVR.className = "babylonVRicon";
  96388. if (this.isInVRMode) {
  96389. this._btnVR.className += " vrdisplaypresenting";
  96390. }
  96391. else {
  96392. if (this._webVRready)
  96393. this._btnVR.className += " vrdisplayready";
  96394. if (this._webVRsupported)
  96395. this._btnVR.className += " vrdisplaysupported";
  96396. if (this._webVRrequesting)
  96397. this._btnVR.className += " vrdisplayrequesting";
  96398. }
  96399. };
  96400. /**
  96401. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  96402. * Otherwise, will use the fullscreen API.
  96403. */
  96404. VRExperienceHelper.prototype.enterVR = function () {
  96405. if (this.onEnteringVRObservable) {
  96406. try {
  96407. this.onEnteringVRObservable.notifyObservers(this);
  96408. }
  96409. catch (err) {
  96410. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  96411. }
  96412. }
  96413. if (this._scene.activeCamera) {
  96414. this._position = this._scene.activeCamera.position.clone();
  96415. // make sure that we return to the last active camera
  96416. this._existingCamera = this._scene.activeCamera;
  96417. }
  96418. if (this._webVRrequesting)
  96419. return;
  96420. // If WebVR is supported and a headset is connected
  96421. if (this._webVRready) {
  96422. if (!this._webVRpresenting) {
  96423. this._webVRCamera.position = this._position;
  96424. this._scene.activeCamera = this._webVRCamera;
  96425. }
  96426. }
  96427. else if (this._vrDeviceOrientationCamera) {
  96428. this._vrDeviceOrientationCamera.position = this._position;
  96429. if (this._scene.activeCamera) {
  96430. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  96431. }
  96432. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  96433. this._scene.getEngine().switchFullscreen(true);
  96434. this.updateButtonVisibility();
  96435. }
  96436. if (this._scene.activeCamera && this._canvas) {
  96437. this._scene.activeCamera.attachControl(this._canvas);
  96438. }
  96439. if (this._interactionsEnabled) {
  96440. this._scene.registerBeforeRender(this.beforeRender);
  96441. }
  96442. this._hasEnteredVR = true;
  96443. };
  96444. /**
  96445. * Attempt to exit VR, or fullscreen.
  96446. */
  96447. VRExperienceHelper.prototype.exitVR = function () {
  96448. if (this._hasEnteredVR) {
  96449. if (this.onExitingVRObservable) {
  96450. try {
  96451. this.onExitingVRObservable.notifyObservers(this);
  96452. }
  96453. catch (err) {
  96454. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  96455. }
  96456. }
  96457. if (this._webVRpresenting) {
  96458. this._scene.getEngine().disableVR();
  96459. }
  96460. if (this._scene.activeCamera) {
  96461. this._position = this._scene.activeCamera.position.clone();
  96462. }
  96463. if (this._deviceOrientationCamera) {
  96464. this._deviceOrientationCamera.position = this._position;
  96465. this._scene.activeCamera = this._deviceOrientationCamera;
  96466. if (this._canvas) {
  96467. this._scene.activeCamera.attachControl(this._canvas);
  96468. }
  96469. }
  96470. else if (this._existingCamera) {
  96471. this._existingCamera.position = this._position;
  96472. this._scene.activeCamera = this._existingCamera;
  96473. }
  96474. this.updateButtonVisibility();
  96475. if (this._interactionsEnabled) {
  96476. this._scene.unregisterBeforeRender(this.beforeRender);
  96477. this._cameraGazer._gazeTracker.isVisible = false;
  96478. if (this._leftController) {
  96479. this._leftController._gazeTracker.isVisible = false;
  96480. }
  96481. if (this._rightController) {
  96482. this._rightController._gazeTracker.isVisible = false;
  96483. }
  96484. }
  96485. // resize to update width and height when exiting vr exits fullscreen
  96486. this._scene.getEngine().resize();
  96487. this._hasEnteredVR = false;
  96488. }
  96489. };
  96490. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  96491. /**
  96492. * The position of the vr experience helper.
  96493. */
  96494. get: function () {
  96495. return this._position;
  96496. },
  96497. /**
  96498. * Sets the position of the vr experience helper.
  96499. */
  96500. set: function (value) {
  96501. this._position = value;
  96502. if (this._scene.activeCamera) {
  96503. this._scene.activeCamera.position = value;
  96504. }
  96505. },
  96506. enumerable: true,
  96507. configurable: true
  96508. });
  96509. /**
  96510. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  96511. */
  96512. VRExperienceHelper.prototype.enableInteractions = function () {
  96513. var _this = this;
  96514. if (!this._interactionsEnabled) {
  96515. this._interactionsRequested = true;
  96516. if (this._leftController) {
  96517. this._enableInteractionOnController(this._leftController);
  96518. }
  96519. if (this._rightController) {
  96520. this._enableInteractionOnController(this._rightController);
  96521. }
  96522. this.raySelectionPredicate = function (mesh) {
  96523. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  96524. };
  96525. this.meshSelectionPredicate = function (mesh) {
  96526. return true;
  96527. };
  96528. this._raySelectionPredicate = function (mesh) {
  96529. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  96530. && mesh.name.indexOf("teleportationTarget") === -1
  96531. && mesh.name.indexOf("torusTeleportation") === -1)) {
  96532. return _this.raySelectionPredicate(mesh);
  96533. }
  96534. return false;
  96535. };
  96536. this._interactionsEnabled = true;
  96537. }
  96538. };
  96539. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  96540. get: function () {
  96541. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  96542. },
  96543. enumerable: true,
  96544. configurable: true
  96545. });
  96546. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  96547. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  96548. if (this._floorMeshesCollection[i].id === mesh.id) {
  96549. return true;
  96550. }
  96551. }
  96552. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  96553. return true;
  96554. }
  96555. return false;
  96556. };
  96557. /**
  96558. * Adds a floor mesh to be used for teleportation.
  96559. * @param floorMesh the mesh to be used for teleportation.
  96560. */
  96561. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  96562. if (!this._floorMeshesCollection) {
  96563. return;
  96564. }
  96565. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  96566. return;
  96567. }
  96568. this._floorMeshesCollection.push(floorMesh);
  96569. };
  96570. /**
  96571. * Removes a floor mesh from being used for teleportation.
  96572. * @param floorMesh the mesh to be removed.
  96573. */
  96574. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  96575. if (!this._floorMeshesCollection) {
  96576. return;
  96577. }
  96578. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  96579. if (meshIndex !== -1) {
  96580. this._floorMeshesCollection.splice(meshIndex, 1);
  96581. }
  96582. };
  96583. /**
  96584. * Enables interactions and teleportation using the VR controllers and gaze.
  96585. * @param vrTeleportationOptions options to modify teleportation behavior.
  96586. */
  96587. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  96588. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  96589. if (!this._teleportationInitialized) {
  96590. this._teleportationRequested = true;
  96591. this.enableInteractions();
  96592. if (vrTeleportationOptions.floorMeshName) {
  96593. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  96594. }
  96595. if (vrTeleportationOptions.floorMeshes) {
  96596. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  96597. }
  96598. if (this._leftController != null) {
  96599. this._enableTeleportationOnController(this._leftController);
  96600. }
  96601. if (this._rightController != null) {
  96602. this._enableTeleportationOnController(this._rightController);
  96603. }
  96604. // Creates an image processing post process for the vignette not relying
  96605. // on the main scene configuration for image processing to reduce setup and spaces
  96606. // (gamma/linear) conflicts.
  96607. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  96608. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  96609. imageProcessingConfiguration.vignetteEnabled = true;
  96610. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  96611. this._webVRCamera.detachPostProcess(this._postProcessMove);
  96612. this._teleportationInitialized = true;
  96613. if (this._isDefaultTeleportationTarget) {
  96614. this._createTeleportationCircles();
  96615. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  96616. }
  96617. }
  96618. };
  96619. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  96620. var _this = this;
  96621. var controllerMesh = controller.webVRController.mesh;
  96622. if (controllerMesh) {
  96623. controller._interactionsEnabled = true;
  96624. controller._activatePointer();
  96625. if (this.webVROptions.laserToggle) {
  96626. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  96627. // Enabling / disabling laserPointer
  96628. if (_this._displayLaserPointer && stateObject.value === 1) {
  96629. if (controller._activePointer) {
  96630. controller._deactivatePointer();
  96631. }
  96632. else {
  96633. controller._activatePointer();
  96634. }
  96635. if (_this.displayGaze) {
  96636. controller._gazeTracker.isVisible = controller._activePointer;
  96637. }
  96638. }
  96639. });
  96640. }
  96641. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  96642. var gazer = controller;
  96643. if (_this._noControllerIsActive) {
  96644. gazer = _this._cameraGazer;
  96645. }
  96646. if (!gazer._pointerDownOnMeshAsked) {
  96647. if (stateObject.value > _this._padSensibilityUp) {
  96648. gazer._selectionPointerDown();
  96649. }
  96650. }
  96651. else if (stateObject.value < _this._padSensibilityDown) {
  96652. gazer._selectionPointerUp();
  96653. }
  96654. });
  96655. }
  96656. };
  96657. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  96658. // Dont teleport if another gaze already requested teleportation
  96659. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  96660. return;
  96661. }
  96662. if (!gazer._teleportationRequestInitiated) {
  96663. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  96664. gazer._activatePointer();
  96665. gazer._teleportationRequestInitiated = true;
  96666. }
  96667. }
  96668. else {
  96669. // Listening to the proper controller values changes to confirm teleportation
  96670. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  96671. if (this._teleportActive) {
  96672. this._teleportCamera(this._haloCenter);
  96673. }
  96674. gazer._teleportationRequestInitiated = false;
  96675. }
  96676. }
  96677. };
  96678. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  96679. // Only rotate when user is not currently selecting a teleportation location
  96680. if (gazer._teleportationRequestInitiated) {
  96681. return;
  96682. }
  96683. if (!gazer._rotationLeftAsked) {
  96684. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  96685. gazer._rotationLeftAsked = true;
  96686. if (this._rotationAllowed) {
  96687. this._rotateCamera(false);
  96688. }
  96689. }
  96690. }
  96691. else {
  96692. if (stateObject.x > -this._padSensibilityDown) {
  96693. gazer._rotationLeftAsked = false;
  96694. }
  96695. }
  96696. if (!gazer._rotationRightAsked) {
  96697. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  96698. gazer._rotationRightAsked = true;
  96699. if (this._rotationAllowed) {
  96700. this._rotateCamera(true);
  96701. }
  96702. }
  96703. }
  96704. else {
  96705. if (stateObject.x < this._padSensibilityDown) {
  96706. gazer._rotationRightAsked = false;
  96707. }
  96708. }
  96709. };
  96710. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  96711. // Only teleport backwards when user is not currently selecting a teleportation location
  96712. if (gazer._teleportationRequestInitiated) {
  96713. return;
  96714. }
  96715. // Teleport backwards
  96716. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  96717. if (!gazer._teleportationBackRequestInitiated) {
  96718. if (!this.currentVRCamera) {
  96719. return;
  96720. }
  96721. // Get rotation and position of the current camera
  96722. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  96723. var position = this.currentVRCamera.position;
  96724. // If the camera has device position, use that instead
  96725. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  96726. rotation = this.currentVRCamera.deviceRotationQuaternion;
  96727. position = this.currentVRCamera.devicePosition;
  96728. }
  96729. // Get matrix with only the y rotation of the device rotation
  96730. rotation.toEulerAnglesToRef(this._workingVector);
  96731. this._workingVector.z = 0;
  96732. this._workingVector.x = 0;
  96733. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  96734. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  96735. // Rotate backwards ray by device rotation to cast at the ground behind the user
  96736. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  96737. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  96738. var ray = new BABYLON.Ray(position, this._workingVector);
  96739. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96740. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  96741. this._teleportCamera(hit.pickedPoint);
  96742. }
  96743. gazer._teleportationBackRequestInitiated = true;
  96744. }
  96745. }
  96746. else {
  96747. gazer._teleportationBackRequestInitiated = false;
  96748. }
  96749. };
  96750. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  96751. var _this = this;
  96752. var controllerMesh = controller.webVRController.mesh;
  96753. if (controllerMesh) {
  96754. if (!controller._interactionsEnabled) {
  96755. this._enableInteractionOnController(controller);
  96756. }
  96757. controller._interactionsEnabled = true;
  96758. controller._teleportationEnabled = true;
  96759. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96760. controller._dpadPressed = false;
  96761. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  96762. controller._dpadPressed = stateObject.pressed;
  96763. if (!controller._dpadPressed) {
  96764. controller._rotationLeftAsked = false;
  96765. controller._rotationRightAsked = false;
  96766. controller._teleportationBackRequestInitiated = false;
  96767. }
  96768. });
  96769. }
  96770. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  96771. if (_this.teleportationEnabled) {
  96772. _this._checkTeleportBackwards(stateObject, controller);
  96773. _this._checkTeleportWithRay(stateObject, controller);
  96774. }
  96775. _this._checkRotate(stateObject, controller);
  96776. });
  96777. }
  96778. };
  96779. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  96780. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  96781. this._teleportationTarget.isPickable = false;
  96782. var length = 512;
  96783. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  96784. dynamicTexture.hasAlpha = true;
  96785. var context = dynamicTexture.getContext();
  96786. var centerX = length / 2;
  96787. var centerY = length / 2;
  96788. var radius = 200;
  96789. context.beginPath();
  96790. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  96791. context.fillStyle = this._teleportationFillColor;
  96792. context.fill();
  96793. context.lineWidth = 10;
  96794. context.strokeStyle = this._teleportationBorderColor;
  96795. context.stroke();
  96796. context.closePath();
  96797. dynamicTexture.update();
  96798. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  96799. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  96800. this._teleportationTarget.material = teleportationCircleMaterial;
  96801. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  96802. torus.isPickable = false;
  96803. torus.parent = this._teleportationTarget;
  96804. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96805. var keys = [];
  96806. keys.push({
  96807. frame: 0,
  96808. value: 0
  96809. });
  96810. keys.push({
  96811. frame: 30,
  96812. value: 0.4
  96813. });
  96814. keys.push({
  96815. frame: 60,
  96816. value: 0
  96817. });
  96818. animationInnerCircle.setKeys(keys);
  96819. var easingFunction = new BABYLON.SineEase();
  96820. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96821. animationInnerCircle.setEasingFunction(easingFunction);
  96822. torus.animations = [];
  96823. torus.animations.push(animationInnerCircle);
  96824. this._scene.beginAnimation(torus, 0, 60, true);
  96825. this._hideTeleportationTarget();
  96826. };
  96827. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  96828. this._teleportActive = true;
  96829. if (this._teleportationInitialized) {
  96830. this._teleportationTarget.isVisible = true;
  96831. if (this._isDefaultTeleportationTarget) {
  96832. this._teleportationTarget.getChildren()[0].isVisible = true;
  96833. }
  96834. }
  96835. };
  96836. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  96837. this._teleportActive = false;
  96838. if (this._teleportationInitialized) {
  96839. this._teleportationTarget.isVisible = false;
  96840. if (this._isDefaultTeleportationTarget) {
  96841. this._teleportationTarget.getChildren()[0].isVisible = false;
  96842. }
  96843. }
  96844. };
  96845. VRExperienceHelper.prototype._rotateCamera = function (right) {
  96846. var _this = this;
  96847. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96848. return;
  96849. }
  96850. if (right) {
  96851. this._rotationAngle++;
  96852. }
  96853. else {
  96854. this._rotationAngle--;
  96855. }
  96856. this.currentVRCamera.animations = [];
  96857. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  96858. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96859. var animationRotationKeys = [];
  96860. animationRotationKeys.push({
  96861. frame: 0,
  96862. value: this.currentVRCamera.rotationQuaternion
  96863. });
  96864. animationRotationKeys.push({
  96865. frame: 6,
  96866. value: target
  96867. });
  96868. animationRotation.setKeys(animationRotationKeys);
  96869. animationRotation.setEasingFunction(this._circleEase);
  96870. this.currentVRCamera.animations.push(animationRotation);
  96871. this._postProcessMove.animations = [];
  96872. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96873. var vignetteWeightKeys = [];
  96874. vignetteWeightKeys.push({
  96875. frame: 0,
  96876. value: 0
  96877. });
  96878. vignetteWeightKeys.push({
  96879. frame: 3,
  96880. value: 4
  96881. });
  96882. vignetteWeightKeys.push({
  96883. frame: 6,
  96884. value: 0
  96885. });
  96886. animationPP.setKeys(vignetteWeightKeys);
  96887. animationPP.setEasingFunction(this._circleEase);
  96888. this._postProcessMove.animations.push(animationPP);
  96889. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96890. var vignetteStretchKeys = [];
  96891. vignetteStretchKeys.push({
  96892. frame: 0,
  96893. value: 0
  96894. });
  96895. vignetteStretchKeys.push({
  96896. frame: 3,
  96897. value: 10
  96898. });
  96899. vignetteStretchKeys.push({
  96900. frame: 6,
  96901. value: 0
  96902. });
  96903. animationPP2.setKeys(vignetteStretchKeys);
  96904. animationPP2.setEasingFunction(this._circleEase);
  96905. this._postProcessMove.animations.push(animationPP2);
  96906. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96907. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96908. this._postProcessMove.samples = 4;
  96909. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96910. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  96911. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96912. });
  96913. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  96914. };
  96915. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  96916. if (hit.pickedPoint) {
  96917. if (gazer._teleportationRequestInitiated) {
  96918. this._displayTeleportationTarget();
  96919. this._haloCenter.copyFrom(hit.pickedPoint);
  96920. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  96921. }
  96922. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  96923. if (pickNormal) {
  96924. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96925. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96926. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  96927. }
  96928. this._teleportationTarget.position.y += 0.1;
  96929. }
  96930. };
  96931. VRExperienceHelper.prototype._teleportCamera = function (location) {
  96932. var _this = this;
  96933. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96934. return;
  96935. }
  96936. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  96937. // offset of the headset from the anchor.
  96938. if (this.webVRCamera.leftCamera) {
  96939. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  96940. this._workingVector.subtractInPlace(this.webVRCamera.position);
  96941. location.subtractToRef(this._workingVector, this._workingVector);
  96942. }
  96943. else {
  96944. this._workingVector.copyFrom(location);
  96945. }
  96946. // Add height to account for user's height offset
  96947. if (this.isInVRMode) {
  96948. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  96949. }
  96950. else {
  96951. this._workingVector.y += this._defaultHeight;
  96952. }
  96953. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  96954. // Create animation from the camera's position to the new location
  96955. this.currentVRCamera.animations = [];
  96956. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96957. var animationCameraTeleportationKeys = [{
  96958. frame: 0,
  96959. value: this.currentVRCamera.position
  96960. },
  96961. {
  96962. frame: 11,
  96963. value: this._workingVector
  96964. }
  96965. ];
  96966. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  96967. animationCameraTeleportation.setEasingFunction(this._circleEase);
  96968. this.currentVRCamera.animations.push(animationCameraTeleportation);
  96969. this._postProcessMove.animations = [];
  96970. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96971. var vignetteWeightKeys = [];
  96972. vignetteWeightKeys.push({
  96973. frame: 0,
  96974. value: 0
  96975. });
  96976. vignetteWeightKeys.push({
  96977. frame: 5,
  96978. value: 8
  96979. });
  96980. vignetteWeightKeys.push({
  96981. frame: 11,
  96982. value: 0
  96983. });
  96984. animationPP.setKeys(vignetteWeightKeys);
  96985. this._postProcessMove.animations.push(animationPP);
  96986. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96987. var vignetteStretchKeys = [];
  96988. vignetteStretchKeys.push({
  96989. frame: 0,
  96990. value: 0
  96991. });
  96992. vignetteStretchKeys.push({
  96993. frame: 5,
  96994. value: 10
  96995. });
  96996. vignetteStretchKeys.push({
  96997. frame: 11,
  96998. value: 0
  96999. });
  97000. animationPP2.setKeys(vignetteStretchKeys);
  97001. this._postProcessMove.animations.push(animationPP2);
  97002. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  97003. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  97004. this._webVRCamera.attachPostProcess(this._postProcessMove);
  97005. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  97006. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  97007. });
  97008. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  97009. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  97010. });
  97011. this._hideTeleportationTarget();
  97012. };
  97013. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  97014. if (normal) {
  97015. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  97016. if (angle < Math.PI / 2) {
  97017. normal.scaleInPlace(-1);
  97018. }
  97019. }
  97020. return normal;
  97021. };
  97022. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  97023. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  97024. return;
  97025. }
  97026. var ray = gazer._getForwardRay(this._rayLength);
  97027. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  97028. if (hit) {
  97029. // Populate the contrllers mesh that can be used for drag/drop
  97030. if (gazer._laserPointer) {
  97031. hit.originMesh = gazer._laserPointer.parent;
  97032. }
  97033. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  97034. }
  97035. gazer._currentHit = hit;
  97036. // Moving the gazeTracker on the mesh face targetted
  97037. if (hit && hit.pickedPoint) {
  97038. if (this._displayGaze) {
  97039. var multiplier = 1;
  97040. gazer._gazeTracker.isVisible = true;
  97041. if (gazer._isActionableMesh) {
  97042. multiplier = 3;
  97043. }
  97044. if (this.updateGazeTrackerScale) {
  97045. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  97046. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  97047. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  97048. }
  97049. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  97050. // To avoid z-fighting
  97051. var deltaFighting = 0.002;
  97052. if (pickNormal) {
  97053. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  97054. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  97055. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  97056. }
  97057. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  97058. if (gazer._gazeTracker.position.x < 0) {
  97059. gazer._gazeTracker.position.x += deltaFighting;
  97060. }
  97061. else {
  97062. gazer._gazeTracker.position.x -= deltaFighting;
  97063. }
  97064. if (gazer._gazeTracker.position.y < 0) {
  97065. gazer._gazeTracker.position.y += deltaFighting;
  97066. }
  97067. else {
  97068. gazer._gazeTracker.position.y -= deltaFighting;
  97069. }
  97070. if (gazer._gazeTracker.position.z < 0) {
  97071. gazer._gazeTracker.position.z += deltaFighting;
  97072. }
  97073. else {
  97074. gazer._gazeTracker.position.z -= deltaFighting;
  97075. }
  97076. }
  97077. // Changing the size of the laser pointer based on the distance from the targetted point
  97078. gazer._updatePointerDistance(hit.distance);
  97079. }
  97080. else {
  97081. gazer._updatePointerDistance();
  97082. gazer._gazeTracker.isVisible = false;
  97083. }
  97084. if (hit && hit.pickedMesh) {
  97085. // The object selected is the floor, we're in a teleportation scenario
  97086. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  97087. // Moving the teleportation area to this targetted point
  97088. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  97089. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  97090. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97091. }
  97092. gazer._currentMeshSelected = null;
  97093. if (gazer._teleportationRequestInitiated) {
  97094. this._moveTeleportationSelectorTo(hit, gazer, ray);
  97095. }
  97096. return;
  97097. }
  97098. // If not, we're in a selection scenario
  97099. //this._teleportationAllowed = false;
  97100. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  97101. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  97102. this.onNewMeshPicked.notifyObservers(hit);
  97103. gazer._currentMeshSelected = hit.pickedMesh;
  97104. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  97105. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  97106. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  97107. gazer._isActionableMesh = true;
  97108. }
  97109. else {
  97110. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97111. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97112. gazer._isActionableMesh = false;
  97113. }
  97114. try {
  97115. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  97116. }
  97117. catch (err) {
  97118. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  97119. }
  97120. }
  97121. else {
  97122. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97123. gazer._currentMeshSelected = null;
  97124. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97125. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97126. }
  97127. }
  97128. }
  97129. else {
  97130. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  97131. gazer._currentMeshSelected = null;
  97132. //this._teleportationAllowed = false;
  97133. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97134. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  97135. }
  97136. };
  97137. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  97138. if (mesh) {
  97139. this.onSelectedMeshUnselected.notifyObservers(mesh);
  97140. }
  97141. };
  97142. /**
  97143. * Sets the color of the laser ray from the vr controllers.
  97144. * @param color new color for the ray.
  97145. */
  97146. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  97147. if (this._leftController) {
  97148. this._leftController._setLaserPointerColor(color);
  97149. }
  97150. if (this._rightController) {
  97151. this._rightController._setLaserPointerColor(color);
  97152. }
  97153. };
  97154. /**
  97155. * Sets the color of the ray from the vr headsets gaze.
  97156. * @param color new color for the ray.
  97157. */
  97158. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  97159. if (!this._cameraGazer._gazeTracker.material) {
  97160. return;
  97161. }
  97162. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  97163. if (this._leftController) {
  97164. this._leftController._gazeTracker.material.emissiveColor = color;
  97165. }
  97166. if (this._rightController) {
  97167. this._rightController._gazeTracker.material.emissiveColor = color;
  97168. }
  97169. };
  97170. /**
  97171. * Exits VR and disposes of the vr experience helper
  97172. */
  97173. VRExperienceHelper.prototype.dispose = function () {
  97174. if (this.isInVRMode) {
  97175. this.exitVR();
  97176. }
  97177. if (this._postProcessMove) {
  97178. this._postProcessMove.dispose();
  97179. }
  97180. if (this._webVRCamera) {
  97181. this._webVRCamera.dispose();
  97182. }
  97183. if (this._vrDeviceOrientationCamera) {
  97184. this._vrDeviceOrientationCamera.dispose();
  97185. }
  97186. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  97187. document.body.removeChild(this._btnVR);
  97188. }
  97189. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  97190. this._deviceOrientationCamera.dispose();
  97191. }
  97192. if (this._cameraGazer) {
  97193. this._cameraGazer.dispose();
  97194. }
  97195. if (this._leftController) {
  97196. this._leftController.dispose();
  97197. }
  97198. if (this._rightController) {
  97199. this._rightController.dispose();
  97200. }
  97201. if (this._teleportationTarget) {
  97202. this._teleportationTarget.dispose();
  97203. }
  97204. this._floorMeshesCollection = [];
  97205. document.removeEventListener("keydown", this._onKeyDown);
  97206. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97207. window.removeEventListener("resize", this._onResize);
  97208. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  97209. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  97210. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  97211. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  97212. document.onmsfullscreenchange = null;
  97213. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  97214. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  97215. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  97216. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97217. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  97218. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  97219. this._scene.unregisterBeforeRender(this.beforeRender);
  97220. };
  97221. /**
  97222. * Gets the name of the VRExperienceHelper class
  97223. * @returns "VRExperienceHelper"
  97224. */
  97225. VRExperienceHelper.prototype.getClassName = function () {
  97226. return "VRExperienceHelper";
  97227. };
  97228. return VRExperienceHelper;
  97229. }());
  97230. BABYLON.VRExperienceHelper = VRExperienceHelper;
  97231. })(BABYLON || (BABYLON = {}));
  97232. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  97233. // Mainly based on these 2 articles :
  97234. // 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
  97235. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  97236. var BABYLON;
  97237. (function (BABYLON) {
  97238. /**
  97239. * Defines the potential axis of a Joystick
  97240. */
  97241. var JoystickAxis;
  97242. (function (JoystickAxis) {
  97243. /** X axis */
  97244. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  97245. /** Y axis */
  97246. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  97247. /** Z axis */
  97248. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  97249. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  97250. /**
  97251. * Class used to define virtual joystick (used in touch mode)
  97252. */
  97253. var VirtualJoystick = /** @class */ (function () {
  97254. /**
  97255. * Creates a new virtual joystick
  97256. * @param leftJoystick defines that the joystick is for left hand (false by default)
  97257. */
  97258. function VirtualJoystick(leftJoystick) {
  97259. var _this = this;
  97260. if (leftJoystick) {
  97261. this._leftJoystick = true;
  97262. }
  97263. else {
  97264. this._leftJoystick = false;
  97265. }
  97266. VirtualJoystick._globalJoystickIndex++;
  97267. // By default left & right arrow keys are moving the X
  97268. // and up & down keys are moving the Y
  97269. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97270. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97271. this.reverseLeftRight = false;
  97272. this.reverseUpDown = false;
  97273. // collections of pointers
  97274. this._touches = new BABYLON.StringDictionary();
  97275. this.deltaPosition = BABYLON.Vector3.Zero();
  97276. this._joystickSensibility = 25;
  97277. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97278. this._onResize = function (evt) {
  97279. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97280. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97281. if (VirtualJoystick.vjCanvas) {
  97282. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  97283. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  97284. }
  97285. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  97286. };
  97287. // injecting a canvas element on top of the canvas 3D game
  97288. if (!VirtualJoystick.vjCanvas) {
  97289. window.addEventListener("resize", this._onResize, false);
  97290. VirtualJoystick.vjCanvas = document.createElement("canvas");
  97291. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  97292. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  97293. VirtualJoystick.vjCanvas.width = window.innerWidth;
  97294. VirtualJoystick.vjCanvas.height = window.innerHeight;
  97295. VirtualJoystick.vjCanvas.style.width = "100%";
  97296. VirtualJoystick.vjCanvas.style.height = "100%";
  97297. VirtualJoystick.vjCanvas.style.position = "absolute";
  97298. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  97299. VirtualJoystick.vjCanvas.style.top = "0px";
  97300. VirtualJoystick.vjCanvas.style.left = "0px";
  97301. VirtualJoystick.vjCanvas.style.zIndex = "5";
  97302. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  97303. // Support for jQuery PEP polyfill
  97304. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  97305. var context = VirtualJoystick.vjCanvas.getContext('2d');
  97306. if (!context) {
  97307. throw new Error("Unable to create canvas for virtual joystick");
  97308. }
  97309. VirtualJoystick.vjCanvasContext = context;
  97310. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  97311. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97312. document.body.appendChild(VirtualJoystick.vjCanvas);
  97313. }
  97314. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  97315. this.pressed = false;
  97316. // default joystick color
  97317. this._joystickColor = "cyan";
  97318. this._joystickPointerID = -1;
  97319. // current joystick position
  97320. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  97321. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  97322. // origin joystick position
  97323. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  97324. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  97325. this._onPointerDownHandlerRef = function (evt) {
  97326. _this._onPointerDown(evt);
  97327. };
  97328. this._onPointerMoveHandlerRef = function (evt) {
  97329. _this._onPointerMove(evt);
  97330. };
  97331. this._onPointerUpHandlerRef = function (evt) {
  97332. _this._onPointerUp(evt);
  97333. };
  97334. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  97335. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  97336. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  97337. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  97338. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  97339. evt.preventDefault(); // Disables system menu
  97340. }, false);
  97341. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97342. }
  97343. /**
  97344. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  97345. * @param newJoystickSensibility defines the new sensibility
  97346. */
  97347. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  97348. this._joystickSensibility = newJoystickSensibility;
  97349. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  97350. };
  97351. VirtualJoystick.prototype._onPointerDown = function (e) {
  97352. var positionOnScreenCondition;
  97353. e.preventDefault();
  97354. if (this._leftJoystick === true) {
  97355. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  97356. }
  97357. else {
  97358. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  97359. }
  97360. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  97361. // First contact will be dedicated to the virtual joystick
  97362. this._joystickPointerID = e.pointerId;
  97363. this._joystickPointerStartPos.x = e.clientX;
  97364. this._joystickPointerStartPos.y = e.clientY;
  97365. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  97366. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  97367. this._deltaJoystickVector.x = 0;
  97368. this._deltaJoystickVector.y = 0;
  97369. this.pressed = true;
  97370. this._touches.add(e.pointerId.toString(), e);
  97371. }
  97372. else {
  97373. // You can only trigger the action buttons with a joystick declared
  97374. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  97375. this._action();
  97376. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  97377. }
  97378. }
  97379. };
  97380. VirtualJoystick.prototype._onPointerMove = function (e) {
  97381. // If the current pointer is the one associated to the joystick (first touch contact)
  97382. if (this._joystickPointerID == e.pointerId) {
  97383. this._joystickPointerPos.x = e.clientX;
  97384. this._joystickPointerPos.y = e.clientY;
  97385. this._deltaJoystickVector = this._joystickPointerPos.clone();
  97386. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  97387. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  97388. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  97389. switch (this._axisTargetedByLeftAndRight) {
  97390. case JoystickAxis.X:
  97391. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  97392. break;
  97393. case JoystickAxis.Y:
  97394. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  97395. break;
  97396. case JoystickAxis.Z:
  97397. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  97398. break;
  97399. }
  97400. var directionUpDown = this.reverseUpDown ? 1 : -1;
  97401. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  97402. switch (this._axisTargetedByUpAndDown) {
  97403. case JoystickAxis.X:
  97404. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  97405. break;
  97406. case JoystickAxis.Y:
  97407. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  97408. break;
  97409. case JoystickAxis.Z:
  97410. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  97411. break;
  97412. }
  97413. }
  97414. else {
  97415. var data = this._touches.get(e.pointerId.toString());
  97416. if (data) {
  97417. data.x = e.clientX;
  97418. data.y = e.clientY;
  97419. }
  97420. }
  97421. };
  97422. VirtualJoystick.prototype._onPointerUp = function (e) {
  97423. if (this._joystickPointerID == e.pointerId) {
  97424. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  97425. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  97426. this._joystickPointerID = -1;
  97427. this.pressed = false;
  97428. }
  97429. else {
  97430. var touch = this._touches.get(e.pointerId.toString());
  97431. if (touch) {
  97432. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97433. }
  97434. }
  97435. this._deltaJoystickVector.x = 0;
  97436. this._deltaJoystickVector.y = 0;
  97437. this._touches.remove(e.pointerId.toString());
  97438. };
  97439. /**
  97440. * Change the color of the virtual joystick
  97441. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  97442. */
  97443. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  97444. this._joystickColor = newColor;
  97445. };
  97446. /**
  97447. * Defines a callback to call when the joystick is touched
  97448. * @param action defines the callback
  97449. */
  97450. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  97451. this._action = action;
  97452. };
  97453. /**
  97454. * Defines which axis you'd like to control for left & right
  97455. * @param axis defines the axis to use
  97456. */
  97457. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  97458. switch (axis) {
  97459. case JoystickAxis.X:
  97460. case JoystickAxis.Y:
  97461. case JoystickAxis.Z:
  97462. this._axisTargetedByLeftAndRight = axis;
  97463. break;
  97464. default:
  97465. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  97466. break;
  97467. }
  97468. };
  97469. /**
  97470. * Defines which axis you'd like to control for up & down
  97471. * @param axis defines the axis to use
  97472. */
  97473. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  97474. switch (axis) {
  97475. case JoystickAxis.X:
  97476. case JoystickAxis.Y:
  97477. case JoystickAxis.Z:
  97478. this._axisTargetedByUpAndDown = axis;
  97479. break;
  97480. default:
  97481. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  97482. break;
  97483. }
  97484. };
  97485. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  97486. var _this = this;
  97487. if (this.pressed) {
  97488. this._touches.forEach(function (key, touch) {
  97489. if (touch.pointerId === _this._joystickPointerID) {
  97490. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  97491. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  97492. VirtualJoystick.vjCanvasContext.beginPath();
  97493. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97494. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97495. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  97496. VirtualJoystick.vjCanvasContext.stroke();
  97497. VirtualJoystick.vjCanvasContext.closePath();
  97498. VirtualJoystick.vjCanvasContext.beginPath();
  97499. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97500. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  97501. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  97502. VirtualJoystick.vjCanvasContext.stroke();
  97503. VirtualJoystick.vjCanvasContext.closePath();
  97504. VirtualJoystick.vjCanvasContext.beginPath();
  97505. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  97506. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  97507. VirtualJoystick.vjCanvasContext.stroke();
  97508. VirtualJoystick.vjCanvasContext.closePath();
  97509. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  97510. }
  97511. else {
  97512. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  97513. VirtualJoystick.vjCanvasContext.beginPath();
  97514. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  97515. VirtualJoystick.vjCanvasContext.beginPath();
  97516. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  97517. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  97518. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  97519. VirtualJoystick.vjCanvasContext.stroke();
  97520. VirtualJoystick.vjCanvasContext.closePath();
  97521. touch.prevX = touch.x;
  97522. touch.prevY = touch.y;
  97523. }
  97524. ;
  97525. });
  97526. }
  97527. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  97528. };
  97529. /**
  97530. * Release internal HTML canvas
  97531. */
  97532. VirtualJoystick.prototype.releaseCanvas = function () {
  97533. if (VirtualJoystick.vjCanvas) {
  97534. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  97535. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  97536. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  97537. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  97538. window.removeEventListener("resize", this._onResize);
  97539. document.body.removeChild(VirtualJoystick.vjCanvas);
  97540. VirtualJoystick.vjCanvas = null;
  97541. }
  97542. };
  97543. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  97544. VirtualJoystick._globalJoystickIndex = 0;
  97545. return VirtualJoystick;
  97546. }());
  97547. BABYLON.VirtualJoystick = VirtualJoystick;
  97548. })(BABYLON || (BABYLON = {}));
  97549. //# sourceMappingURL=babylon.virtualJoystick.js.map
  97550. var BABYLON;
  97551. (function (BABYLON) {
  97552. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  97553. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  97554. });
  97555. // We're mainly based on the logic defined into the FreeCamera code
  97556. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  97557. __extends(VirtualJoysticksCamera, _super);
  97558. function VirtualJoysticksCamera(name, position, scene) {
  97559. var _this = _super.call(this, name, position, scene) || this;
  97560. _this.inputs.addVirtualJoystick();
  97561. return _this;
  97562. }
  97563. VirtualJoysticksCamera.prototype.getClassName = function () {
  97564. return "VirtualJoysticksCamera";
  97565. };
  97566. return VirtualJoysticksCamera;
  97567. }(BABYLON.FreeCamera));
  97568. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  97569. })(BABYLON || (BABYLON = {}));
  97570. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  97571. var BABYLON;
  97572. (function (BABYLON) {
  97573. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  97574. function FreeCameraVirtualJoystickInput() {
  97575. }
  97576. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  97577. return this._leftjoystick;
  97578. };
  97579. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  97580. return this._rightjoystick;
  97581. };
  97582. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  97583. if (this._leftjoystick) {
  97584. var camera = this.camera;
  97585. var speed = camera._computeLocalCameraSpeed() * 50;
  97586. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  97587. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  97588. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  97589. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  97590. if (!this._leftjoystick.pressed) {
  97591. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  97592. }
  97593. if (!this._rightjoystick.pressed) {
  97594. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  97595. }
  97596. }
  97597. };
  97598. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  97599. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  97600. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  97601. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  97602. this._leftjoystick.setJoystickSensibility(0.15);
  97603. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  97604. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  97605. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  97606. this._rightjoystick.reverseUpDown = true;
  97607. this._rightjoystick.setJoystickSensibility(0.05);
  97608. this._rightjoystick.setJoystickColor("yellow");
  97609. };
  97610. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  97611. this._leftjoystick.releaseCanvas();
  97612. this._rightjoystick.releaseCanvas();
  97613. };
  97614. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  97615. return "FreeCameraVirtualJoystickInput";
  97616. };
  97617. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  97618. return "virtualJoystick";
  97619. };
  97620. return FreeCameraVirtualJoystickInput;
  97621. }());
  97622. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  97623. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  97624. })(BABYLON || (BABYLON = {}));
  97625. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  97626. var BABYLON;
  97627. (function (BABYLON) {
  97628. var SimplificationSettings = /** @class */ (function () {
  97629. function SimplificationSettings(quality, distance, optimizeMesh) {
  97630. this.quality = quality;
  97631. this.distance = distance;
  97632. this.optimizeMesh = optimizeMesh;
  97633. }
  97634. return SimplificationSettings;
  97635. }());
  97636. BABYLON.SimplificationSettings = SimplificationSettings;
  97637. var SimplificationQueue = /** @class */ (function () {
  97638. function SimplificationQueue() {
  97639. this.running = false;
  97640. this._simplificationArray = [];
  97641. }
  97642. SimplificationQueue.prototype.addTask = function (task) {
  97643. this._simplificationArray.push(task);
  97644. };
  97645. SimplificationQueue.prototype.executeNext = function () {
  97646. var task = this._simplificationArray.pop();
  97647. if (task) {
  97648. this.running = true;
  97649. this.runSimplification(task);
  97650. }
  97651. else {
  97652. this.running = false;
  97653. }
  97654. };
  97655. SimplificationQueue.prototype.runSimplification = function (task) {
  97656. var _this = this;
  97657. if (task.parallelProcessing) {
  97658. //parallel simplifier
  97659. task.settings.forEach(function (setting) {
  97660. var simplifier = _this.getSimplifier(task);
  97661. simplifier.simplify(setting, function (newMesh) {
  97662. task.mesh.addLODLevel(setting.distance, newMesh);
  97663. newMesh.isVisible = true;
  97664. //check if it is the last
  97665. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  97666. //all done, run the success callback.
  97667. task.successCallback();
  97668. }
  97669. _this.executeNext();
  97670. });
  97671. });
  97672. }
  97673. else {
  97674. //single simplifier.
  97675. var simplifier = this.getSimplifier(task);
  97676. var runDecimation = function (setting, callback) {
  97677. simplifier.simplify(setting, function (newMesh) {
  97678. task.mesh.addLODLevel(setting.distance, newMesh);
  97679. newMesh.isVisible = true;
  97680. //run the next quality level
  97681. callback();
  97682. });
  97683. };
  97684. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  97685. runDecimation(task.settings[loop.index], function () {
  97686. loop.executeNext();
  97687. });
  97688. }, function () {
  97689. //execution ended, run the success callback.
  97690. if (task.successCallback) {
  97691. task.successCallback();
  97692. }
  97693. _this.executeNext();
  97694. });
  97695. }
  97696. };
  97697. SimplificationQueue.prototype.getSimplifier = function (task) {
  97698. switch (task.simplificationType) {
  97699. case SimplificationType.QUADRATIC:
  97700. default:
  97701. return new QuadraticErrorSimplification(task.mesh);
  97702. }
  97703. };
  97704. return SimplificationQueue;
  97705. }());
  97706. BABYLON.SimplificationQueue = SimplificationQueue;
  97707. /**
  97708. * The implemented types of simplification
  97709. * At the moment only Quadratic Error Decimation is implemented
  97710. */
  97711. var SimplificationType;
  97712. (function (SimplificationType) {
  97713. /** Quadratic error decimation */
  97714. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  97715. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  97716. var DecimationTriangle = /** @class */ (function () {
  97717. function DecimationTriangle(vertices) {
  97718. this.vertices = vertices;
  97719. this.error = new Array(4);
  97720. this.deleted = false;
  97721. this.isDirty = false;
  97722. this.deletePending = false;
  97723. this.borderFactor = 0;
  97724. }
  97725. return DecimationTriangle;
  97726. }());
  97727. BABYLON.DecimationTriangle = DecimationTriangle;
  97728. var DecimationVertex = /** @class */ (function () {
  97729. function DecimationVertex(position, id) {
  97730. this.position = position;
  97731. this.id = id;
  97732. this.isBorder = true;
  97733. this.q = new QuadraticMatrix();
  97734. this.triangleCount = 0;
  97735. this.triangleStart = 0;
  97736. this.originalOffsets = [];
  97737. }
  97738. DecimationVertex.prototype.updatePosition = function (newPosition) {
  97739. this.position.copyFrom(newPosition);
  97740. };
  97741. return DecimationVertex;
  97742. }());
  97743. BABYLON.DecimationVertex = DecimationVertex;
  97744. var QuadraticMatrix = /** @class */ (function () {
  97745. function QuadraticMatrix(data) {
  97746. this.data = new Array(10);
  97747. for (var i = 0; i < 10; ++i) {
  97748. if (data && data[i]) {
  97749. this.data[i] = data[i];
  97750. }
  97751. else {
  97752. this.data[i] = 0;
  97753. }
  97754. }
  97755. }
  97756. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  97757. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  97758. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  97759. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  97760. return det;
  97761. };
  97762. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  97763. for (var i = 0; i < 10; ++i) {
  97764. this.data[i] += matrix.data[i];
  97765. }
  97766. };
  97767. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  97768. for (var i = 0; i < 10; ++i) {
  97769. this.data[i] += data[i];
  97770. }
  97771. };
  97772. QuadraticMatrix.prototype.add = function (matrix) {
  97773. var m = new QuadraticMatrix();
  97774. for (var i = 0; i < 10; ++i) {
  97775. m.data[i] = this.data[i] + matrix.data[i];
  97776. }
  97777. return m;
  97778. };
  97779. QuadraticMatrix.FromData = function (a, b, c, d) {
  97780. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  97781. };
  97782. //returning an array to avoid garbage collection
  97783. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  97784. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  97785. };
  97786. return QuadraticMatrix;
  97787. }());
  97788. BABYLON.QuadraticMatrix = QuadraticMatrix;
  97789. var Reference = /** @class */ (function () {
  97790. function Reference(vertexId, triangleId) {
  97791. this.vertexId = vertexId;
  97792. this.triangleId = triangleId;
  97793. }
  97794. return Reference;
  97795. }());
  97796. BABYLON.Reference = Reference;
  97797. /**
  97798. * An implementation of the Quadratic Error simplification algorithm.
  97799. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97800. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  97801. * @author RaananW
  97802. */
  97803. var QuadraticErrorSimplification = /** @class */ (function () {
  97804. function QuadraticErrorSimplification(_mesh) {
  97805. this._mesh = _mesh;
  97806. this.syncIterations = 5000;
  97807. this.aggressiveness = 7;
  97808. this.decimationIterations = 100;
  97809. this.boundingBoxEpsilon = BABYLON.Epsilon;
  97810. }
  97811. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  97812. var _this = this;
  97813. this.initDecimatedMesh();
  97814. //iterating through the submeshes array, one after the other.
  97815. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  97816. _this.initWithMesh(loop.index, function () {
  97817. _this.runDecimation(settings, loop.index, function () {
  97818. loop.executeNext();
  97819. });
  97820. }, settings.optimizeMesh);
  97821. }, function () {
  97822. setTimeout(function () {
  97823. successCallback(_this._reconstructedMesh);
  97824. }, 0);
  97825. });
  97826. };
  97827. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  97828. var _this = this;
  97829. var targetCount = ~~(this.triangles.length * settings.quality);
  97830. var deletedTriangles = 0;
  97831. var triangleCount = this.triangles.length;
  97832. var iterationFunction = function (iteration, callback) {
  97833. setTimeout(function () {
  97834. if (iteration % 5 === 0) {
  97835. _this.updateMesh(iteration === 0);
  97836. }
  97837. for (var i = 0; i < _this.triangles.length; ++i) {
  97838. _this.triangles[i].isDirty = false;
  97839. }
  97840. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  97841. var trianglesIterator = function (i) {
  97842. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  97843. var t = _this.triangles[tIdx];
  97844. if (!t)
  97845. return;
  97846. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  97847. return;
  97848. }
  97849. for (var j = 0; j < 3; ++j) {
  97850. if (t.error[j] < threshold) {
  97851. var deleted0 = [];
  97852. var deleted1 = [];
  97853. var v0 = t.vertices[j];
  97854. var v1 = t.vertices[(j + 1) % 3];
  97855. if (v0.isBorder || v1.isBorder)
  97856. continue;
  97857. var p = BABYLON.Vector3.Zero();
  97858. var n = BABYLON.Vector3.Zero();
  97859. var uv = BABYLON.Vector2.Zero();
  97860. var color = new BABYLON.Color4(0, 0, 0, 1);
  97861. _this.calculateError(v0, v1, p, n, uv, color);
  97862. var delTr = new Array();
  97863. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  97864. continue;
  97865. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  97866. continue;
  97867. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  97868. continue;
  97869. var uniqueArray = new Array();
  97870. delTr.forEach(function (deletedT) {
  97871. if (uniqueArray.indexOf(deletedT) === -1) {
  97872. deletedT.deletePending = true;
  97873. uniqueArray.push(deletedT);
  97874. }
  97875. });
  97876. if (uniqueArray.length % 2 !== 0) {
  97877. continue;
  97878. }
  97879. v0.q = v1.q.add(v0.q);
  97880. v0.updatePosition(p);
  97881. var tStart = _this.references.length;
  97882. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  97883. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  97884. var tCount = _this.references.length - tStart;
  97885. if (tCount <= v0.triangleCount) {
  97886. if (tCount) {
  97887. for (var c = 0; c < tCount; c++) {
  97888. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  97889. }
  97890. }
  97891. }
  97892. else {
  97893. v0.triangleStart = tStart;
  97894. }
  97895. v0.triangleCount = tCount;
  97896. break;
  97897. }
  97898. }
  97899. };
  97900. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  97901. }, 0);
  97902. };
  97903. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  97904. if (triangleCount - deletedTriangles <= targetCount)
  97905. loop.breakLoop();
  97906. else {
  97907. iterationFunction(loop.index, function () {
  97908. loop.executeNext();
  97909. });
  97910. }
  97911. }, function () {
  97912. setTimeout(function () {
  97913. //reconstruct this part of the mesh
  97914. _this.reconstructMesh(submeshIndex);
  97915. successCallback();
  97916. }, 0);
  97917. });
  97918. };
  97919. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  97920. var _this = this;
  97921. this.vertices = [];
  97922. this.triangles = [];
  97923. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97924. var indices = this._mesh.getIndices();
  97925. var submesh = this._mesh.subMeshes[submeshIndex];
  97926. var findInVertices = function (positionToSearch) {
  97927. if (optimizeMesh) {
  97928. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  97929. if (_this.vertices[ii].position.equals(positionToSearch)) {
  97930. return _this.vertices[ii];
  97931. }
  97932. }
  97933. }
  97934. return null;
  97935. };
  97936. var vertexReferences = [];
  97937. var vertexInit = function (i) {
  97938. if (!positionData) {
  97939. return;
  97940. }
  97941. var offset = i + submesh.verticesStart;
  97942. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  97943. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  97944. vertex.originalOffsets.push(offset);
  97945. if (vertex.id === _this.vertices.length) {
  97946. _this.vertices.push(vertex);
  97947. }
  97948. vertexReferences.push(vertex.id);
  97949. };
  97950. //var totalVertices = mesh.getTotalVertices();
  97951. var totalVertices = submesh.verticesCount;
  97952. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  97953. var indicesInit = function (i) {
  97954. if (!indices) {
  97955. return;
  97956. }
  97957. var offset = (submesh.indexStart / 3) + i;
  97958. var pos = (offset * 3);
  97959. var i0 = indices[pos + 0];
  97960. var i1 = indices[pos + 1];
  97961. var i2 = indices[pos + 2];
  97962. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  97963. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  97964. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  97965. var triangle = new DecimationTriangle([v0, v1, v2]);
  97966. triangle.originalOffset = pos;
  97967. _this.triangles.push(triangle);
  97968. };
  97969. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  97970. _this.init(callback);
  97971. });
  97972. });
  97973. };
  97974. QuadraticErrorSimplification.prototype.init = function (callback) {
  97975. var _this = this;
  97976. var triangleInit1 = function (i) {
  97977. var t = _this.triangles[i];
  97978. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  97979. for (var j = 0; j < 3; j++) {
  97980. 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))));
  97981. }
  97982. };
  97983. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  97984. var triangleInit2 = function (i) {
  97985. var t = _this.triangles[i];
  97986. for (var j = 0; j < 3; ++j) {
  97987. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  97988. }
  97989. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  97990. };
  97991. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  97992. callback();
  97993. });
  97994. });
  97995. };
  97996. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  97997. var newTriangles = [];
  97998. var i;
  97999. for (i = 0; i < this.vertices.length; ++i) {
  98000. this.vertices[i].triangleCount = 0;
  98001. }
  98002. var t;
  98003. var j;
  98004. for (i = 0; i < this.triangles.length; ++i) {
  98005. if (!this.triangles[i].deleted) {
  98006. t = this.triangles[i];
  98007. for (j = 0; j < 3; ++j) {
  98008. t.vertices[j].triangleCount = 1;
  98009. }
  98010. newTriangles.push(t);
  98011. }
  98012. }
  98013. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  98014. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  98015. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  98016. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  98017. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  98018. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  98019. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  98020. var vertexCount = 0;
  98021. for (i = 0; i < this.vertices.length; ++i) {
  98022. var vertex = this.vertices[i];
  98023. vertex.id = vertexCount;
  98024. if (vertex.triangleCount) {
  98025. vertex.originalOffsets.forEach(function (originalOffset) {
  98026. if (!normalData) {
  98027. return;
  98028. }
  98029. newPositionData.push(vertex.position.x);
  98030. newPositionData.push(vertex.position.y);
  98031. newPositionData.push(vertex.position.z);
  98032. newNormalData.push(normalData[originalOffset * 3]);
  98033. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  98034. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  98035. if (uvs && uvs.length) {
  98036. newUVsData.push(uvs[(originalOffset * 2)]);
  98037. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  98038. }
  98039. else if (colorsData && colorsData.length) {
  98040. newColorsData.push(colorsData[(originalOffset * 4)]);
  98041. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  98042. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  98043. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  98044. }
  98045. ++vertexCount;
  98046. });
  98047. }
  98048. }
  98049. var startingIndex = this._reconstructedMesh.getTotalIndices();
  98050. var startingVertex = this._reconstructedMesh.getTotalVertices();
  98051. var submeshesArray = this._reconstructedMesh.subMeshes;
  98052. this._reconstructedMesh.subMeshes = [];
  98053. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  98054. var originalIndices = this._mesh.getIndices();
  98055. for (i = 0; i < newTriangles.length; ++i) {
  98056. t = newTriangles[i]; //now get the new referencing point for each vertex
  98057. [0, 1, 2].forEach(function (idx) {
  98058. var id = originalIndices[t.originalOffset + idx];
  98059. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  98060. if (offset < 0)
  98061. offset = 0;
  98062. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  98063. });
  98064. }
  98065. //overwriting the old vertex buffers and indices.
  98066. this._reconstructedMesh.setIndices(newIndicesArray);
  98067. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  98068. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  98069. if (newUVsData.length > 0)
  98070. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  98071. if (newColorsData.length > 0)
  98072. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  98073. //create submesh
  98074. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  98075. if (submeshIndex > 0) {
  98076. this._reconstructedMesh.subMeshes = [];
  98077. submeshesArray.forEach(function (submesh) {
  98078. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  98079. });
  98080. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  98081. }
  98082. };
  98083. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  98084. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  98085. this._reconstructedMesh.material = this._mesh.material;
  98086. this._reconstructedMesh.parent = this._mesh.parent;
  98087. this._reconstructedMesh.isVisible = false;
  98088. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  98089. };
  98090. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  98091. for (var i = 0; i < vertex1.triangleCount; ++i) {
  98092. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  98093. if (t.deleted)
  98094. continue;
  98095. var s = this.references[vertex1.triangleStart + i].vertexId;
  98096. var v1 = t.vertices[(s + 1) % 3];
  98097. var v2 = t.vertices[(s + 2) % 3];
  98098. if ((v1 === vertex2 || v2 === vertex2)) {
  98099. deletedArray[i] = true;
  98100. delTr.push(t);
  98101. continue;
  98102. }
  98103. var d1 = v1.position.subtract(point);
  98104. d1 = d1.normalize();
  98105. var d2 = v2.position.subtract(point);
  98106. d2 = d2.normalize();
  98107. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  98108. return true;
  98109. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  98110. deletedArray[i] = false;
  98111. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  98112. return true;
  98113. }
  98114. return false;
  98115. };
  98116. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  98117. var newDeleted = deletedTriangles;
  98118. for (var i = 0; i < vertex.triangleCount; ++i) {
  98119. var ref = this.references[vertex.triangleStart + i];
  98120. var t = this.triangles[ref.triangleId];
  98121. if (t.deleted)
  98122. continue;
  98123. if (deletedArray[i] && t.deletePending) {
  98124. t.deleted = true;
  98125. newDeleted++;
  98126. continue;
  98127. }
  98128. t.vertices[ref.vertexId] = origVertex;
  98129. t.isDirty = true;
  98130. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  98131. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  98132. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  98133. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  98134. this.references.push(ref);
  98135. }
  98136. return newDeleted;
  98137. };
  98138. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  98139. for (var i = 0; i < this.vertices.length; ++i) {
  98140. var vCount = [];
  98141. var vId = [];
  98142. var v = this.vertices[i];
  98143. var j;
  98144. for (j = 0; j < v.triangleCount; ++j) {
  98145. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  98146. for (var ii = 0; ii < 3; ii++) {
  98147. var ofs = 0;
  98148. var vv = triangle.vertices[ii];
  98149. while (ofs < vCount.length) {
  98150. if (vId[ofs] === vv.id)
  98151. break;
  98152. ++ofs;
  98153. }
  98154. if (ofs === vCount.length) {
  98155. vCount.push(1);
  98156. vId.push(vv.id);
  98157. }
  98158. else {
  98159. vCount[ofs]++;
  98160. }
  98161. }
  98162. }
  98163. for (j = 0; j < vCount.length; ++j) {
  98164. if (vCount[j] === 1) {
  98165. this.vertices[vId[j]].isBorder = true;
  98166. }
  98167. else {
  98168. this.vertices[vId[j]].isBorder = false;
  98169. }
  98170. }
  98171. }
  98172. };
  98173. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  98174. if (identifyBorders === void 0) { identifyBorders = false; }
  98175. var i;
  98176. if (!identifyBorders) {
  98177. var newTrianglesVector = [];
  98178. for (i = 0; i < this.triangles.length; ++i) {
  98179. if (!this.triangles[i].deleted) {
  98180. newTrianglesVector.push(this.triangles[i]);
  98181. }
  98182. }
  98183. this.triangles = newTrianglesVector;
  98184. }
  98185. for (i = 0; i < this.vertices.length; ++i) {
  98186. this.vertices[i].triangleCount = 0;
  98187. this.vertices[i].triangleStart = 0;
  98188. }
  98189. var t;
  98190. var j;
  98191. var v;
  98192. for (i = 0; i < this.triangles.length; ++i) {
  98193. t = this.triangles[i];
  98194. for (j = 0; j < 3; ++j) {
  98195. v = t.vertices[j];
  98196. v.triangleCount++;
  98197. }
  98198. }
  98199. var tStart = 0;
  98200. for (i = 0; i < this.vertices.length; ++i) {
  98201. this.vertices[i].triangleStart = tStart;
  98202. tStart += this.vertices[i].triangleCount;
  98203. this.vertices[i].triangleCount = 0;
  98204. }
  98205. var newReferences = new Array(this.triangles.length * 3);
  98206. for (i = 0; i < this.triangles.length; ++i) {
  98207. t = this.triangles[i];
  98208. for (j = 0; j < 3; ++j) {
  98209. v = t.vertices[j];
  98210. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  98211. v.triangleCount++;
  98212. }
  98213. }
  98214. this.references = newReferences;
  98215. if (identifyBorders) {
  98216. this.identifyBorder();
  98217. }
  98218. };
  98219. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  98220. var x = point.x;
  98221. var y = point.y;
  98222. var z = point.z;
  98223. 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
  98224. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  98225. };
  98226. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  98227. var q = vertex1.q.add(vertex2.q);
  98228. var border = vertex1.isBorder && vertex2.isBorder;
  98229. var error = 0;
  98230. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  98231. if (qDet !== 0 && !border) {
  98232. if (!pointResult) {
  98233. pointResult = BABYLON.Vector3.Zero();
  98234. }
  98235. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  98236. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  98237. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  98238. error = this.vertexError(q, pointResult);
  98239. }
  98240. else {
  98241. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  98242. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  98243. var error1 = this.vertexError(q, vertex1.position);
  98244. var error2 = this.vertexError(q, vertex2.position);
  98245. var error3 = this.vertexError(q, p3);
  98246. error = Math.min(error1, error2, error3);
  98247. if (error === error1) {
  98248. if (pointResult) {
  98249. pointResult.copyFrom(vertex1.position);
  98250. }
  98251. }
  98252. else if (error === error2) {
  98253. if (pointResult) {
  98254. pointResult.copyFrom(vertex2.position);
  98255. }
  98256. }
  98257. else {
  98258. if (pointResult) {
  98259. pointResult.copyFrom(p3);
  98260. }
  98261. }
  98262. }
  98263. return error;
  98264. };
  98265. return QuadraticErrorSimplification;
  98266. }());
  98267. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  98268. })(BABYLON || (BABYLON = {}));
  98269. //# sourceMappingURL=babylon.meshSimplification.js.map
  98270. var BABYLON;
  98271. (function (BABYLON) {
  98272. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  98273. get: function () {
  98274. if (!this._simplificationQueue) {
  98275. this._simplificationQueue = new BABYLON.SimplificationQueue();
  98276. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  98277. if (!component) {
  98278. component = new SimplicationQueueSceneComponent(this);
  98279. this._addComponent(component);
  98280. }
  98281. }
  98282. return this._simplificationQueue;
  98283. },
  98284. set: function (value) {
  98285. this._simplificationQueue = value;
  98286. },
  98287. enumerable: true,
  98288. configurable: true
  98289. });
  98290. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  98291. if (parallelProcessing === void 0) { parallelProcessing = true; }
  98292. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  98293. this.getScene().simplificationQueue.addTask({
  98294. settings: settings,
  98295. parallelProcessing: parallelProcessing,
  98296. mesh: this,
  98297. simplificationType: simplificationType,
  98298. successCallback: successCallback
  98299. });
  98300. return this;
  98301. };
  98302. /**
  98303. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  98304. * created in a scene
  98305. */
  98306. var SimplicationQueueSceneComponent = /** @class */ (function () {
  98307. /**
  98308. * Creates a new instance of the component for the given scene
  98309. * @param scene Defines the scene to register the component in
  98310. */
  98311. function SimplicationQueueSceneComponent(scene) {
  98312. /**
  98313. * The component name helpfull to identify the component in the list of scene components.
  98314. */
  98315. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  98316. this.scene = scene;
  98317. }
  98318. /**
  98319. * Registers the component in a given scene
  98320. */
  98321. SimplicationQueueSceneComponent.prototype.register = function () {
  98322. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  98323. };
  98324. /**
  98325. * Rebuilds the elements related to this component in case of
  98326. * context lost for instance.
  98327. */
  98328. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  98329. // Nothing to do for this component
  98330. };
  98331. /**
  98332. * Disposes the component and the associated ressources
  98333. */
  98334. SimplicationQueueSceneComponent.prototype.dispose = function () {
  98335. // Nothing to do for this component
  98336. };
  98337. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  98338. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  98339. this.scene._simplificationQueue.executeNext();
  98340. }
  98341. };
  98342. return SimplicationQueueSceneComponent;
  98343. }());
  98344. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  98345. })(BABYLON || (BABYLON = {}));
  98346. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  98347. var BABYLON;
  98348. (function (BABYLON) {
  98349. var MeshLODLevel = /** @class */ (function () {
  98350. function MeshLODLevel(distance, mesh) {
  98351. this.distance = distance;
  98352. this.mesh = mesh;
  98353. }
  98354. return MeshLODLevel;
  98355. }());
  98356. BABYLON.MeshLODLevel = MeshLODLevel;
  98357. })(BABYLON || (BABYLON = {}));
  98358. //# sourceMappingURL=babylon.meshLODLevel.js.map
  98359. var BABYLON;
  98360. (function (BABYLON) {
  98361. /**
  98362. * Defines the root class used to create scene optimization to use with SceneOptimizer
  98363. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98364. */
  98365. var SceneOptimization = /** @class */ (function () {
  98366. /**
  98367. * Creates the SceneOptimization object
  98368. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98369. * @param desc defines the description associated with the optimization
  98370. */
  98371. function SceneOptimization(
  98372. /**
  98373. * Defines the priority of this optimization (0 by default which means first in the list)
  98374. */
  98375. priority) {
  98376. if (priority === void 0) { priority = 0; }
  98377. this.priority = priority;
  98378. }
  98379. /**
  98380. * Gets a string describing the action executed by the current optimization
  98381. * @returns description string
  98382. */
  98383. SceneOptimization.prototype.getDescription = function () {
  98384. return "";
  98385. };
  98386. /**
  98387. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98388. * @param scene defines the current scene where to apply this optimization
  98389. * @param optimizer defines the current optimizer
  98390. * @returns true if everything that can be done was applied
  98391. */
  98392. SceneOptimization.prototype.apply = function (scene, optimizer) {
  98393. return true;
  98394. };
  98395. ;
  98396. return SceneOptimization;
  98397. }());
  98398. BABYLON.SceneOptimization = SceneOptimization;
  98399. /**
  98400. * Defines an optimization used to reduce the size of render target textures
  98401. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98402. */
  98403. var TextureOptimization = /** @class */ (function (_super) {
  98404. __extends(TextureOptimization, _super);
  98405. /**
  98406. * Creates the TextureOptimization object
  98407. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98408. * @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
  98409. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98410. */
  98411. function TextureOptimization(
  98412. /**
  98413. * Defines the priority of this optimization (0 by default which means first in the list)
  98414. */
  98415. priority,
  98416. /**
  98417. * 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
  98418. */
  98419. maximumSize,
  98420. /**
  98421. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  98422. */
  98423. step) {
  98424. if (priority === void 0) { priority = 0; }
  98425. if (maximumSize === void 0) { maximumSize = 1024; }
  98426. if (step === void 0) { step = 0.5; }
  98427. var _this = _super.call(this, priority) || this;
  98428. _this.priority = priority;
  98429. _this.maximumSize = maximumSize;
  98430. _this.step = step;
  98431. return _this;
  98432. }
  98433. /**
  98434. * Gets a string describing the action executed by the current optimization
  98435. * @returns description string
  98436. */
  98437. TextureOptimization.prototype.getDescription = function () {
  98438. return "Reducing render target texture size to " + this.maximumSize;
  98439. };
  98440. /**
  98441. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98442. * @param scene defines the current scene where to apply this optimization
  98443. * @param optimizer defines the current optimizer
  98444. * @returns true if everything that can be done was applied
  98445. */
  98446. TextureOptimization.prototype.apply = function (scene, optimizer) {
  98447. var allDone = true;
  98448. for (var index = 0; index < scene.textures.length; index++) {
  98449. var texture = scene.textures[index];
  98450. if (!texture.canRescale || texture.getContext) {
  98451. continue;
  98452. }
  98453. var currentSize = texture.getSize();
  98454. var maxDimension = Math.max(currentSize.width, currentSize.height);
  98455. if (maxDimension > this.maximumSize) {
  98456. texture.scale(this.step);
  98457. allDone = false;
  98458. }
  98459. }
  98460. return allDone;
  98461. };
  98462. return TextureOptimization;
  98463. }(SceneOptimization));
  98464. BABYLON.TextureOptimization = TextureOptimization;
  98465. /**
  98466. * Defines an optimization used to increase or decrease the rendering resolution
  98467. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98468. */
  98469. var HardwareScalingOptimization = /** @class */ (function (_super) {
  98470. __extends(HardwareScalingOptimization, _super);
  98471. /**
  98472. * Creates the HardwareScalingOptimization object
  98473. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98474. * @param maximumScale defines the maximum scale to use (2 by default)
  98475. * @param step defines the step to use between two passes (0.5 by default)
  98476. */
  98477. function HardwareScalingOptimization(
  98478. /**
  98479. * Defines the priority of this optimization (0 by default which means first in the list)
  98480. */
  98481. priority,
  98482. /**
  98483. * Defines the maximum scale to use (2 by default)
  98484. */
  98485. maximumScale,
  98486. /**
  98487. * Defines the step to use between two passes (0.5 by default)
  98488. */
  98489. step) {
  98490. if (priority === void 0) { priority = 0; }
  98491. if (maximumScale === void 0) { maximumScale = 2; }
  98492. if (step === void 0) { step = 0.25; }
  98493. var _this = _super.call(this, priority) || this;
  98494. _this.priority = priority;
  98495. _this.maximumScale = maximumScale;
  98496. _this.step = step;
  98497. _this._currentScale = -1;
  98498. _this._directionOffset = 1;
  98499. return _this;
  98500. }
  98501. /**
  98502. * Gets a string describing the action executed by the current optimization
  98503. * @return description string
  98504. */
  98505. HardwareScalingOptimization.prototype.getDescription = function () {
  98506. return "Setting hardware scaling level to " + this._currentScale;
  98507. };
  98508. /**
  98509. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98510. * @param scene defines the current scene where to apply this optimization
  98511. * @param optimizer defines the current optimizer
  98512. * @returns true if everything that can be done was applied
  98513. */
  98514. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  98515. if (this._currentScale === -1) {
  98516. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  98517. if (this._currentScale > this.maximumScale) {
  98518. this._directionOffset = -1;
  98519. }
  98520. }
  98521. this._currentScale += this._directionOffset * this.step;
  98522. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  98523. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  98524. };
  98525. ;
  98526. return HardwareScalingOptimization;
  98527. }(SceneOptimization));
  98528. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  98529. /**
  98530. * Defines an optimization used to remove shadows
  98531. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98532. */
  98533. var ShadowsOptimization = /** @class */ (function (_super) {
  98534. __extends(ShadowsOptimization, _super);
  98535. function ShadowsOptimization() {
  98536. return _super !== null && _super.apply(this, arguments) || this;
  98537. }
  98538. /**
  98539. * Gets a string describing the action executed by the current optimization
  98540. * @return description string
  98541. */
  98542. ShadowsOptimization.prototype.getDescription = function () {
  98543. return "Turning shadows on/off";
  98544. };
  98545. /**
  98546. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98547. * @param scene defines the current scene where to apply this optimization
  98548. * @param optimizer defines the current optimizer
  98549. * @returns true if everything that can be done was applied
  98550. */
  98551. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  98552. scene.shadowsEnabled = optimizer.isInImprovementMode;
  98553. return true;
  98554. };
  98555. ;
  98556. return ShadowsOptimization;
  98557. }(SceneOptimization));
  98558. BABYLON.ShadowsOptimization = ShadowsOptimization;
  98559. /**
  98560. * Defines an optimization used to turn post-processes off
  98561. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98562. */
  98563. var PostProcessesOptimization = /** @class */ (function (_super) {
  98564. __extends(PostProcessesOptimization, _super);
  98565. function PostProcessesOptimization() {
  98566. return _super !== null && _super.apply(this, arguments) || this;
  98567. }
  98568. /**
  98569. * Gets a string describing the action executed by the current optimization
  98570. * @return description string
  98571. */
  98572. PostProcessesOptimization.prototype.getDescription = function () {
  98573. return "Turning post-processes on/off";
  98574. };
  98575. /**
  98576. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98577. * @param scene defines the current scene where to apply this optimization
  98578. * @param optimizer defines the current optimizer
  98579. * @returns true if everything that can be done was applied
  98580. */
  98581. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  98582. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  98583. return true;
  98584. };
  98585. ;
  98586. return PostProcessesOptimization;
  98587. }(SceneOptimization));
  98588. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  98589. /**
  98590. * Defines an optimization used to turn lens flares off
  98591. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98592. */
  98593. var LensFlaresOptimization = /** @class */ (function (_super) {
  98594. __extends(LensFlaresOptimization, _super);
  98595. function LensFlaresOptimization() {
  98596. return _super !== null && _super.apply(this, arguments) || this;
  98597. }
  98598. /**
  98599. * Gets a string describing the action executed by the current optimization
  98600. * @return description string
  98601. */
  98602. LensFlaresOptimization.prototype.getDescription = function () {
  98603. return "Turning lens flares on/off";
  98604. };
  98605. /**
  98606. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98607. * @param scene defines the current scene where to apply this optimization
  98608. * @param optimizer defines the current optimizer
  98609. * @returns true if everything that can be done was applied
  98610. */
  98611. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  98612. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  98613. return true;
  98614. };
  98615. ;
  98616. return LensFlaresOptimization;
  98617. }(SceneOptimization));
  98618. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  98619. /**
  98620. * Defines an optimization based on user defined callback.
  98621. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98622. */
  98623. var CustomOptimization = /** @class */ (function (_super) {
  98624. __extends(CustomOptimization, _super);
  98625. function CustomOptimization() {
  98626. return _super !== null && _super.apply(this, arguments) || this;
  98627. }
  98628. /**
  98629. * Gets a string describing the action executed by the current optimization
  98630. * @returns description string
  98631. */
  98632. CustomOptimization.prototype.getDescription = function () {
  98633. if (this.onGetDescription) {
  98634. return this.onGetDescription();
  98635. }
  98636. return "Running user defined callback";
  98637. };
  98638. /**
  98639. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98640. * @param scene defines the current scene where to apply this optimization
  98641. * @param optimizer defines the current optimizer
  98642. * @returns true if everything that can be done was applied
  98643. */
  98644. CustomOptimization.prototype.apply = function (scene, optimizer) {
  98645. if (this.onApply) {
  98646. return this.onApply(scene, optimizer);
  98647. }
  98648. return true;
  98649. };
  98650. ;
  98651. return CustomOptimization;
  98652. }(SceneOptimization));
  98653. BABYLON.CustomOptimization = CustomOptimization;
  98654. /**
  98655. * Defines an optimization used to turn particles off
  98656. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98657. */
  98658. var ParticlesOptimization = /** @class */ (function (_super) {
  98659. __extends(ParticlesOptimization, _super);
  98660. function ParticlesOptimization() {
  98661. return _super !== null && _super.apply(this, arguments) || this;
  98662. }
  98663. /**
  98664. * Gets a string describing the action executed by the current optimization
  98665. * @return description string
  98666. */
  98667. ParticlesOptimization.prototype.getDescription = function () {
  98668. return "Turning particles on/off";
  98669. };
  98670. /**
  98671. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98672. * @param scene defines the current scene where to apply this optimization
  98673. * @param optimizer defines the current optimizer
  98674. * @returns true if everything that can be done was applied
  98675. */
  98676. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  98677. scene.particlesEnabled = optimizer.isInImprovementMode;
  98678. return true;
  98679. };
  98680. ;
  98681. return ParticlesOptimization;
  98682. }(SceneOptimization));
  98683. BABYLON.ParticlesOptimization = ParticlesOptimization;
  98684. /**
  98685. * Defines an optimization used to turn render targets off
  98686. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98687. */
  98688. var RenderTargetsOptimization = /** @class */ (function (_super) {
  98689. __extends(RenderTargetsOptimization, _super);
  98690. function RenderTargetsOptimization() {
  98691. return _super !== null && _super.apply(this, arguments) || this;
  98692. }
  98693. /**
  98694. * Gets a string describing the action executed by the current optimization
  98695. * @return description string
  98696. */
  98697. RenderTargetsOptimization.prototype.getDescription = function () {
  98698. return "Turning render targets off";
  98699. };
  98700. /**
  98701. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98702. * @param scene defines the current scene where to apply this optimization
  98703. * @param optimizer defines the current optimizer
  98704. * @returns true if everything that can be done was applied
  98705. */
  98706. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  98707. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  98708. return true;
  98709. };
  98710. ;
  98711. return RenderTargetsOptimization;
  98712. }(SceneOptimization));
  98713. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  98714. /**
  98715. * Defines an optimization used to merge meshes with compatible materials
  98716. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98717. */
  98718. var MergeMeshesOptimization = /** @class */ (function (_super) {
  98719. __extends(MergeMeshesOptimization, _super);
  98720. function MergeMeshesOptimization() {
  98721. var _this = _super !== null && _super.apply(this, arguments) || this;
  98722. _this._canBeMerged = function (abstractMesh) {
  98723. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  98724. return false;
  98725. }
  98726. var mesh = abstractMesh;
  98727. if (mesh.isDisposed()) {
  98728. return false;
  98729. }
  98730. if (!mesh.isVisible || !mesh.isEnabled()) {
  98731. return false;
  98732. }
  98733. if (mesh.instances.length > 0) {
  98734. return false;
  98735. }
  98736. if (mesh.skeleton || mesh.hasLODLevels) {
  98737. return false;
  98738. }
  98739. return true;
  98740. };
  98741. return _this;
  98742. }
  98743. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  98744. /**
  98745. * Gets or sets a boolean which defines if optimization octree has to be updated
  98746. */
  98747. get: function () {
  98748. return MergeMeshesOptimization._UpdateSelectionTree;
  98749. },
  98750. /**
  98751. * Gets or sets a boolean which defines if optimization octree has to be updated
  98752. */
  98753. set: function (value) {
  98754. MergeMeshesOptimization._UpdateSelectionTree = value;
  98755. },
  98756. enumerable: true,
  98757. configurable: true
  98758. });
  98759. /**
  98760. * Gets a string describing the action executed by the current optimization
  98761. * @return description string
  98762. */
  98763. MergeMeshesOptimization.prototype.getDescription = function () {
  98764. return "Merging similar meshes together";
  98765. };
  98766. /**
  98767. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  98768. * @param scene defines the current scene where to apply this optimization
  98769. * @param optimizer defines the current optimizer
  98770. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  98771. * @returns true if everything that can be done was applied
  98772. */
  98773. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  98774. var globalPool = scene.meshes.slice(0);
  98775. var globalLength = globalPool.length;
  98776. for (var index = 0; index < globalLength; index++) {
  98777. var currentPool = new Array();
  98778. var current = globalPool[index];
  98779. // Checks
  98780. if (!this._canBeMerged(current)) {
  98781. continue;
  98782. }
  98783. currentPool.push(current);
  98784. // Find compatible meshes
  98785. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  98786. var otherMesh = globalPool[subIndex];
  98787. if (!this._canBeMerged(otherMesh)) {
  98788. continue;
  98789. }
  98790. if (otherMesh.material !== current.material) {
  98791. continue;
  98792. }
  98793. if (otherMesh.checkCollisions !== current.checkCollisions) {
  98794. continue;
  98795. }
  98796. currentPool.push(otherMesh);
  98797. globalLength--;
  98798. globalPool.splice(subIndex, 1);
  98799. subIndex--;
  98800. }
  98801. if (currentPool.length < 2) {
  98802. continue;
  98803. }
  98804. // Merge meshes
  98805. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  98806. }
  98807. if (updateSelectionTree != undefined) {
  98808. if (updateSelectionTree) {
  98809. scene.createOrUpdateSelectionOctree();
  98810. }
  98811. }
  98812. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  98813. scene.createOrUpdateSelectionOctree();
  98814. }
  98815. return true;
  98816. };
  98817. ;
  98818. MergeMeshesOptimization._UpdateSelectionTree = false;
  98819. return MergeMeshesOptimization;
  98820. }(SceneOptimization));
  98821. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  98822. /**
  98823. * Defines a list of options used by SceneOptimizer
  98824. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98825. */
  98826. var SceneOptimizerOptions = /** @class */ (function () {
  98827. /**
  98828. * Creates a new list of options used by SceneOptimizer
  98829. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  98830. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  98831. */
  98832. function SceneOptimizerOptions(
  98833. /**
  98834. * Defines the target frame rate to reach (60 by default)
  98835. */
  98836. targetFrameRate,
  98837. /**
  98838. * Defines the interval between two checkes (2000ms by default)
  98839. */
  98840. trackerDuration) {
  98841. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  98842. if (trackerDuration === void 0) { trackerDuration = 2000; }
  98843. this.targetFrameRate = targetFrameRate;
  98844. this.trackerDuration = trackerDuration;
  98845. /**
  98846. * Gets the list of optimizations to apply
  98847. */
  98848. this.optimizations = new Array();
  98849. }
  98850. /**
  98851. * Add a new optimization
  98852. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  98853. * @returns the current SceneOptimizerOptions
  98854. */
  98855. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  98856. this.optimizations.push(optimization);
  98857. return this;
  98858. };
  98859. /**
  98860. * Add a new custom optimization
  98861. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  98862. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  98863. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  98864. * @returns the current SceneOptimizerOptions
  98865. */
  98866. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  98867. if (priority === void 0) { priority = 0; }
  98868. var optimization = new CustomOptimization(priority);
  98869. optimization.onApply = onApply;
  98870. optimization.onGetDescription = onGetDescription;
  98871. this.optimizations.push(optimization);
  98872. return this;
  98873. };
  98874. /**
  98875. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  98876. * @param targetFrameRate defines the target frame rate (60 by default)
  98877. * @returns a SceneOptimizerOptions object
  98878. */
  98879. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  98880. var result = new SceneOptimizerOptions(targetFrameRate);
  98881. var priority = 0;
  98882. result.addOptimization(new MergeMeshesOptimization(priority));
  98883. result.addOptimization(new ShadowsOptimization(priority));
  98884. result.addOptimization(new LensFlaresOptimization(priority));
  98885. // Next priority
  98886. priority++;
  98887. result.addOptimization(new PostProcessesOptimization(priority));
  98888. result.addOptimization(new ParticlesOptimization(priority));
  98889. // Next priority
  98890. priority++;
  98891. result.addOptimization(new TextureOptimization(priority, 1024));
  98892. return result;
  98893. };
  98894. /**
  98895. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  98896. * @param targetFrameRate defines the target frame rate (60 by default)
  98897. * @returns a SceneOptimizerOptions object
  98898. */
  98899. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  98900. var result = new SceneOptimizerOptions(targetFrameRate);
  98901. var priority = 0;
  98902. result.addOptimization(new MergeMeshesOptimization(priority));
  98903. result.addOptimization(new ShadowsOptimization(priority));
  98904. result.addOptimization(new LensFlaresOptimization(priority));
  98905. // Next priority
  98906. priority++;
  98907. result.addOptimization(new PostProcessesOptimization(priority));
  98908. result.addOptimization(new ParticlesOptimization(priority));
  98909. // Next priority
  98910. priority++;
  98911. result.addOptimization(new TextureOptimization(priority, 512));
  98912. // Next priority
  98913. priority++;
  98914. result.addOptimization(new RenderTargetsOptimization(priority));
  98915. // Next priority
  98916. priority++;
  98917. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  98918. return result;
  98919. };
  98920. /**
  98921. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  98922. * @param targetFrameRate defines the target frame rate (60 by default)
  98923. * @returns a SceneOptimizerOptions object
  98924. */
  98925. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  98926. var result = new SceneOptimizerOptions(targetFrameRate);
  98927. var priority = 0;
  98928. result.addOptimization(new MergeMeshesOptimization(priority));
  98929. result.addOptimization(new ShadowsOptimization(priority));
  98930. result.addOptimization(new LensFlaresOptimization(priority));
  98931. // Next priority
  98932. priority++;
  98933. result.addOptimization(new PostProcessesOptimization(priority));
  98934. result.addOptimization(new ParticlesOptimization(priority));
  98935. // Next priority
  98936. priority++;
  98937. result.addOptimization(new TextureOptimization(priority, 256));
  98938. // Next priority
  98939. priority++;
  98940. result.addOptimization(new RenderTargetsOptimization(priority));
  98941. // Next priority
  98942. priority++;
  98943. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  98944. return result;
  98945. };
  98946. return SceneOptimizerOptions;
  98947. }());
  98948. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  98949. /**
  98950. * Class used to run optimizations in order to reach a target frame rate
  98951. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98952. */
  98953. var SceneOptimizer = /** @class */ (function () {
  98954. /**
  98955. * Creates a new SceneOptimizer
  98956. * @param scene defines the scene to work on
  98957. * @param options defines the options to use with the SceneOptimizer
  98958. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  98959. * @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)
  98960. */
  98961. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  98962. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  98963. if (improvementMode === void 0) { improvementMode = false; }
  98964. var _this = this;
  98965. this._isRunning = false;
  98966. this._currentPriorityLevel = 0;
  98967. this._targetFrameRate = 60;
  98968. this._trackerDuration = 2000;
  98969. this._currentFrameRate = 0;
  98970. this._improvementMode = false;
  98971. /**
  98972. * Defines an observable called when the optimizer reaches the target frame rate
  98973. */
  98974. this.onSuccessObservable = new BABYLON.Observable();
  98975. /**
  98976. * Defines an observable called when the optimizer enables an optimization
  98977. */
  98978. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  98979. /**
  98980. * Defines an observable called when the optimizer is not able to reach the target frame rate
  98981. */
  98982. this.onFailureObservable = new BABYLON.Observable();
  98983. if (!options) {
  98984. this._options = new SceneOptimizerOptions();
  98985. }
  98986. else {
  98987. this._options = options;
  98988. }
  98989. if (this._options.targetFrameRate) {
  98990. this._targetFrameRate = this._options.targetFrameRate;
  98991. }
  98992. if (this._options.trackerDuration) {
  98993. this._trackerDuration = this._options.trackerDuration;
  98994. }
  98995. if (autoGeneratePriorities) {
  98996. var priority = 0;
  98997. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  98998. var optim = _a[_i];
  98999. optim.priority = priority++;
  99000. }
  99001. }
  99002. this._improvementMode = improvementMode;
  99003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99004. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  99005. _this._sceneDisposeObserver = null;
  99006. _this.dispose();
  99007. });
  99008. }
  99009. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  99010. /**
  99011. * Gets a boolean indicating if the optimizer is in improvement mode
  99012. */
  99013. get: function () {
  99014. return this._improvementMode;
  99015. },
  99016. enumerable: true,
  99017. configurable: true
  99018. });
  99019. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  99020. /**
  99021. * Gets the current priority level (0 at start)
  99022. */
  99023. get: function () {
  99024. return this._currentPriorityLevel;
  99025. },
  99026. enumerable: true,
  99027. configurable: true
  99028. });
  99029. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  99030. /**
  99031. * Gets the current frame rate checked by the SceneOptimizer
  99032. */
  99033. get: function () {
  99034. return this._currentFrameRate;
  99035. },
  99036. enumerable: true,
  99037. configurable: true
  99038. });
  99039. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  99040. /**
  99041. * Gets or sets the current target frame rate (60 by default)
  99042. */
  99043. get: function () {
  99044. return this._targetFrameRate;
  99045. },
  99046. /**
  99047. * Gets or sets the current target frame rate (60 by default)
  99048. */
  99049. set: function (value) {
  99050. this._targetFrameRate = value;
  99051. },
  99052. enumerable: true,
  99053. configurable: true
  99054. });
  99055. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  99056. /**
  99057. * Gets or sets the current interval between two checks (every 2000ms by default)
  99058. */
  99059. get: function () {
  99060. return this._trackerDuration;
  99061. },
  99062. /**
  99063. * Gets or sets the current interval between two checks (every 2000ms by default)
  99064. */
  99065. set: function (value) {
  99066. this._trackerDuration = value;
  99067. },
  99068. enumerable: true,
  99069. configurable: true
  99070. });
  99071. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  99072. /**
  99073. * Gets the list of active optimizations
  99074. */
  99075. get: function () {
  99076. return this._options.optimizations;
  99077. },
  99078. enumerable: true,
  99079. configurable: true
  99080. });
  99081. /**
  99082. * Stops the current optimizer
  99083. */
  99084. SceneOptimizer.prototype.stop = function () {
  99085. this._isRunning = false;
  99086. };
  99087. /**
  99088. * Reset the optimizer to initial step (current priority level = 0)
  99089. */
  99090. SceneOptimizer.prototype.reset = function () {
  99091. this._currentPriorityLevel = 0;
  99092. };
  99093. /**
  99094. * Start the optimizer. By default it will try to reach a specific framerate
  99095. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  99096. */
  99097. SceneOptimizer.prototype.start = function () {
  99098. var _this = this;
  99099. if (this._isRunning) {
  99100. return;
  99101. }
  99102. this._isRunning = true;
  99103. // Let's wait for the scene to be ready before running our check
  99104. this._scene.executeWhenReady(function () {
  99105. setTimeout(function () {
  99106. _this._checkCurrentState();
  99107. }, _this._trackerDuration);
  99108. });
  99109. };
  99110. SceneOptimizer.prototype._checkCurrentState = function () {
  99111. var _this = this;
  99112. if (!this._isRunning) {
  99113. return;
  99114. }
  99115. var scene = this._scene;
  99116. var options = this._options;
  99117. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  99118. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  99119. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  99120. this._isRunning = false;
  99121. this.onSuccessObservable.notifyObservers(this);
  99122. return;
  99123. }
  99124. // Apply current level of optimizations
  99125. var allDone = true;
  99126. var noOptimizationApplied = true;
  99127. for (var index = 0; index < options.optimizations.length; index++) {
  99128. var optimization = options.optimizations[index];
  99129. if (optimization.priority === this._currentPriorityLevel) {
  99130. noOptimizationApplied = false;
  99131. allDone = allDone && optimization.apply(scene, this);
  99132. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  99133. }
  99134. }
  99135. // If no optimization was applied, this is a failure :(
  99136. if (noOptimizationApplied) {
  99137. this._isRunning = false;
  99138. this.onFailureObservable.notifyObservers(this);
  99139. return;
  99140. }
  99141. // If all optimizations were done, move to next level
  99142. if (allDone) {
  99143. this._currentPriorityLevel++;
  99144. }
  99145. // Let's the system running for a specific amount of time before checking FPS
  99146. scene.executeWhenReady(function () {
  99147. setTimeout(function () {
  99148. _this._checkCurrentState();
  99149. }, _this._trackerDuration);
  99150. });
  99151. };
  99152. /**
  99153. * Release all resources
  99154. */
  99155. SceneOptimizer.prototype.dispose = function () {
  99156. this.stop();
  99157. this.onSuccessObservable.clear();
  99158. this.onFailureObservable.clear();
  99159. this.onNewOptimizationAppliedObservable.clear();
  99160. if (this._sceneDisposeObserver) {
  99161. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99162. }
  99163. };
  99164. /**
  99165. * Helper function to create a SceneOptimizer with one single line of code
  99166. * @param scene defines the scene to work on
  99167. * @param options defines the options to use with the SceneOptimizer
  99168. * @param onSuccess defines a callback to call on success
  99169. * @param onFailure defines a callback to call on failure
  99170. * @returns the new SceneOptimizer object
  99171. */
  99172. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  99173. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  99174. if (onSuccess) {
  99175. optimizer.onSuccessObservable.add(function () {
  99176. onSuccess();
  99177. });
  99178. }
  99179. if (onFailure) {
  99180. optimizer.onFailureObservable.add(function () {
  99181. onFailure();
  99182. });
  99183. }
  99184. optimizer.start();
  99185. return optimizer;
  99186. };
  99187. return SceneOptimizer;
  99188. }());
  99189. BABYLON.SceneOptimizer = SceneOptimizer;
  99190. })(BABYLON || (BABYLON = {}));
  99191. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  99192. var BABYLON;
  99193. (function (BABYLON) {
  99194. var OutlineRenderer = /** @class */ (function () {
  99195. function OutlineRenderer(scene) {
  99196. this.zOffset = 1;
  99197. this._scene = scene;
  99198. }
  99199. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  99200. var _this = this;
  99201. if (useOverlay === void 0) { useOverlay = false; }
  99202. var scene = this._scene;
  99203. var engine = this._scene.getEngine();
  99204. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99205. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  99206. return;
  99207. }
  99208. var mesh = subMesh.getRenderingMesh();
  99209. var material = subMesh.getMaterial();
  99210. if (!material || !scene.activeCamera) {
  99211. return;
  99212. }
  99213. engine.enableEffect(this._effect);
  99214. // Logarithmic depth
  99215. if (material.useLogarithmicDepth) {
  99216. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  99217. }
  99218. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  99219. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  99220. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  99221. // Bones
  99222. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99223. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99224. }
  99225. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  99226. // Alpha test
  99227. if (material && material.needAlphaTesting()) {
  99228. var alphaTexture = material.getAlphaTestTexture();
  99229. if (alphaTexture) {
  99230. this._effect.setTexture("diffuseSampler", alphaTexture);
  99231. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  99232. }
  99233. }
  99234. engine.setZOffset(-this.zOffset);
  99235. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  99236. engine.setZOffset(0);
  99237. };
  99238. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  99239. var defines = [];
  99240. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  99241. var mesh = subMesh.getMesh();
  99242. var material = subMesh.getMaterial();
  99243. if (material) {
  99244. // Alpha test
  99245. if (material.needAlphaTesting()) {
  99246. defines.push("#define ALPHATEST");
  99247. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99248. attribs.push(BABYLON.VertexBuffer.UVKind);
  99249. defines.push("#define UV1");
  99250. }
  99251. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  99252. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99253. defines.push("#define UV2");
  99254. }
  99255. }
  99256. //Logarithmic depth
  99257. if (material.useLogarithmicDepth) {
  99258. defines.push("#define LOGARITHMICDEPTH");
  99259. }
  99260. }
  99261. // Bones
  99262. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99263. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99264. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99265. if (mesh.numBoneInfluencers > 4) {
  99266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99268. }
  99269. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99270. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  99271. }
  99272. else {
  99273. defines.push("#define NUM_BONE_INFLUENCERS 0");
  99274. }
  99275. // Instances
  99276. if (useInstances) {
  99277. defines.push("#define INSTANCES");
  99278. attribs.push("world0");
  99279. attribs.push("world1");
  99280. attribs.push("world2");
  99281. attribs.push("world3");
  99282. }
  99283. // Get correct effect
  99284. var join = defines.join("\n");
  99285. if (this._cachedDefines !== join) {
  99286. this._cachedDefines = join;
  99287. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  99288. }
  99289. return this._effect.isReady();
  99290. };
  99291. return OutlineRenderer;
  99292. }());
  99293. BABYLON.OutlineRenderer = OutlineRenderer;
  99294. })(BABYLON || (BABYLON = {}));
  99295. //# sourceMappingURL=babylon.outlineRenderer.js.map
  99296. var BABYLON;
  99297. (function (BABYLON) {
  99298. /**
  99299. * FaceAdjacencies Helper class to generate edges
  99300. */
  99301. var FaceAdjacencies = /** @class */ (function () {
  99302. function FaceAdjacencies() {
  99303. this.edges = new Array();
  99304. this.edgesConnectedCount = 0;
  99305. }
  99306. return FaceAdjacencies;
  99307. }());
  99308. /**
  99309. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  99310. */
  99311. var EdgesRenderer = /** @class */ (function () {
  99312. /**
  99313. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  99314. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  99315. * @param source Mesh used to create edges
  99316. * @param epsilon sum of angles in adjacency to check for edge
  99317. * @param checkVerticesInsteadOfIndices
  99318. * @param generateEdgesLines - should generate Lines or only prepare resources.
  99319. */
  99320. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  99321. if (epsilon === void 0) { epsilon = 0.95; }
  99322. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99323. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  99324. this.edgesWidthScalerForOrthographic = 1000.0;
  99325. this.edgesWidthScalerForPerspective = 50.0;
  99326. this._linesPositions = new Array();
  99327. this._linesNormals = new Array();
  99328. this._linesIndices = new Array();
  99329. this._buffers = {};
  99330. this._checkVerticesInsteadOfIndices = false;
  99331. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  99332. this.isEnabled = true;
  99333. this._source = source;
  99334. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  99335. this._epsilon = epsilon;
  99336. this._prepareRessources();
  99337. if (generateEdgesLines) {
  99338. this._generateEdgesLines();
  99339. }
  99340. }
  99341. EdgesRenderer.prototype._prepareRessources = function () {
  99342. if (this._lineShader) {
  99343. return;
  99344. }
  99345. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  99346. attributes: ["position", "normal"],
  99347. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  99348. });
  99349. this._lineShader.disableDepthWrite = true;
  99350. this._lineShader.backFaceCulling = false;
  99351. };
  99352. /** @hidden */
  99353. EdgesRenderer.prototype._rebuild = function () {
  99354. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99355. if (buffer) {
  99356. buffer._rebuild();
  99357. }
  99358. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99359. if (buffer) {
  99360. buffer._rebuild();
  99361. }
  99362. var scene = this._source.getScene();
  99363. var engine = scene.getEngine();
  99364. this._ib = engine.createIndexBuffer(this._linesIndices);
  99365. };
  99366. /**
  99367. * Releases the required resources for the edges renderer
  99368. */
  99369. EdgesRenderer.prototype.dispose = function () {
  99370. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  99371. if (buffer) {
  99372. buffer.dispose();
  99373. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  99374. }
  99375. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  99376. if (buffer) {
  99377. buffer.dispose();
  99378. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  99379. }
  99380. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  99381. this._lineShader.dispose();
  99382. };
  99383. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  99384. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  99385. return 0;
  99386. }
  99387. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  99388. return 1;
  99389. }
  99390. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  99391. return 2;
  99392. }
  99393. return -1;
  99394. };
  99395. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  99396. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  99397. return 0;
  99398. }
  99399. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  99400. return 1;
  99401. }
  99402. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  99403. return 2;
  99404. }
  99405. return -1;
  99406. };
  99407. /**
  99408. * Checks if the pair of p0 and p1 is en edge
  99409. * @param faceIndex
  99410. * @param edge
  99411. * @param faceNormals
  99412. * @param p0
  99413. * @param p1
  99414. * @private
  99415. */
  99416. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99417. var needToCreateLine;
  99418. if (edge === undefined) {
  99419. needToCreateLine = true;
  99420. }
  99421. else {
  99422. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  99423. needToCreateLine = dotProduct < this._epsilon;
  99424. }
  99425. if (needToCreateLine) {
  99426. var offset = this._linesPositions.length / 3;
  99427. var normal = p0.subtract(p1);
  99428. normal.normalize();
  99429. // Positions
  99430. this._linesPositions.push(p0.x);
  99431. this._linesPositions.push(p0.y);
  99432. this._linesPositions.push(p0.z);
  99433. this._linesPositions.push(p0.x);
  99434. this._linesPositions.push(p0.y);
  99435. this._linesPositions.push(p0.z);
  99436. this._linesPositions.push(p1.x);
  99437. this._linesPositions.push(p1.y);
  99438. this._linesPositions.push(p1.z);
  99439. this._linesPositions.push(p1.x);
  99440. this._linesPositions.push(p1.y);
  99441. this._linesPositions.push(p1.z);
  99442. // Normals
  99443. this._linesNormals.push(p1.x);
  99444. this._linesNormals.push(p1.y);
  99445. this._linesNormals.push(p1.z);
  99446. this._linesNormals.push(-1);
  99447. this._linesNormals.push(p1.x);
  99448. this._linesNormals.push(p1.y);
  99449. this._linesNormals.push(p1.z);
  99450. this._linesNormals.push(1);
  99451. this._linesNormals.push(p0.x);
  99452. this._linesNormals.push(p0.y);
  99453. this._linesNormals.push(p0.z);
  99454. this._linesNormals.push(-1);
  99455. this._linesNormals.push(p0.x);
  99456. this._linesNormals.push(p0.y);
  99457. this._linesNormals.push(p0.z);
  99458. this._linesNormals.push(1);
  99459. // Indices
  99460. this._linesIndices.push(offset);
  99461. this._linesIndices.push(offset + 1);
  99462. this._linesIndices.push(offset + 2);
  99463. this._linesIndices.push(offset);
  99464. this._linesIndices.push(offset + 2);
  99465. this._linesIndices.push(offset + 3);
  99466. }
  99467. };
  99468. /**
  99469. * Generates lines edges from adjacencjes
  99470. * @private
  99471. */
  99472. EdgesRenderer.prototype._generateEdgesLines = function () {
  99473. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99474. var indices = this._source.getIndices();
  99475. if (!indices || !positions) {
  99476. return;
  99477. }
  99478. // First let's find adjacencies
  99479. var adjacencies = new Array();
  99480. var faceNormals = new Array();
  99481. var index;
  99482. var faceAdjacencies;
  99483. // Prepare faces
  99484. for (index = 0; index < indices.length; index += 3) {
  99485. faceAdjacencies = new FaceAdjacencies();
  99486. var p0Index = indices[index];
  99487. var p1Index = indices[index + 1];
  99488. var p2Index = indices[index + 2];
  99489. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  99490. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  99491. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  99492. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  99493. faceNormal.normalize();
  99494. faceNormals.push(faceNormal);
  99495. adjacencies.push(faceAdjacencies);
  99496. }
  99497. // Scan
  99498. for (index = 0; index < adjacencies.length; index++) {
  99499. faceAdjacencies = adjacencies[index];
  99500. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  99501. var otherFaceAdjacencies = adjacencies[otherIndex];
  99502. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  99503. break;
  99504. }
  99505. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  99506. continue;
  99507. }
  99508. var otherP0 = indices[otherIndex * 3];
  99509. var otherP1 = indices[otherIndex * 3 + 1];
  99510. var otherP2 = indices[otherIndex * 3 + 2];
  99511. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  99512. var otherEdgeIndex = 0;
  99513. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  99514. continue;
  99515. }
  99516. switch (edgeIndex) {
  99517. case 0:
  99518. if (this._checkVerticesInsteadOfIndices) {
  99519. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99520. }
  99521. else {
  99522. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  99523. }
  99524. break;
  99525. case 1:
  99526. if (this._checkVerticesInsteadOfIndices) {
  99527. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99528. }
  99529. else {
  99530. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  99531. }
  99532. break;
  99533. case 2:
  99534. if (this._checkVerticesInsteadOfIndices) {
  99535. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  99536. }
  99537. else {
  99538. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  99539. }
  99540. break;
  99541. }
  99542. if (otherEdgeIndex === -1) {
  99543. continue;
  99544. }
  99545. faceAdjacencies.edges[edgeIndex] = otherIndex;
  99546. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  99547. faceAdjacencies.edgesConnectedCount++;
  99548. otherFaceAdjacencies.edgesConnectedCount++;
  99549. if (faceAdjacencies.edgesConnectedCount === 3) {
  99550. break;
  99551. }
  99552. }
  99553. }
  99554. }
  99555. // Create lines
  99556. for (index = 0; index < adjacencies.length; index++) {
  99557. // 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
  99558. var current = adjacencies[index];
  99559. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99560. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  99561. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  99562. }
  99563. // Merge into a single mesh
  99564. var engine = this._source.getScene().getEngine();
  99565. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99566. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99567. this._ib = engine.createIndexBuffer(this._linesIndices);
  99568. this._indicesCount = this._linesIndices.length;
  99569. };
  99570. EdgesRenderer.prototype.render = function () {
  99571. var scene = this._source.getScene();
  99572. if (!this._lineShader.isReady() || !scene.activeCamera) {
  99573. return;
  99574. }
  99575. var engine = scene.getEngine();
  99576. this._lineShader._preBind();
  99577. if (this._source.edgesColor.a !== 1) {
  99578. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  99579. }
  99580. else {
  99581. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99582. }
  99583. // VBOs
  99584. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  99585. scene.resetCachedMaterial();
  99586. this._lineShader.setColor4("color", this._source.edgesColor);
  99587. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  99588. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  99589. }
  99590. else {
  99591. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  99592. }
  99593. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  99594. this._lineShader.bind(this._source.getWorldMatrix());
  99595. // Draw order
  99596. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  99597. this._lineShader.unbind();
  99598. };
  99599. return EdgesRenderer;
  99600. }());
  99601. BABYLON.EdgesRenderer = EdgesRenderer;
  99602. })(BABYLON || (BABYLON = {}));
  99603. //# sourceMappingURL=babylon.edgesRenderer.js.map
  99604. var BABYLON;
  99605. (function (BABYLON) {
  99606. /**
  99607. * FaceAdjacencies Helper class to generate edges
  99608. */
  99609. var FaceAdjacencies = /** @class */ (function () {
  99610. function FaceAdjacencies() {
  99611. this.edges = new Array();
  99612. this.edgesConnectedCount = 0;
  99613. }
  99614. return FaceAdjacencies;
  99615. }());
  99616. /**
  99617. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  99618. */
  99619. var LineEdgesRenderer = /** @class */ (function (_super) {
  99620. __extends(LineEdgesRenderer, _super);
  99621. /**
  99622. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  99623. * @param source LineMesh used to generate edges
  99624. * @param epsilon not important (specified angle for edge detection)
  99625. * @param checkVerticesInsteadOfIndices not important for LineMesh
  99626. */
  99627. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  99628. if (epsilon === void 0) { epsilon = 0.95; }
  99629. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  99630. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  99631. _this._generateEdgesLines();
  99632. return _this;
  99633. }
  99634. /**
  99635. * Always create the edge since its a line so only important things are p0 and p1
  99636. * @param faceIndex not important for LineMesh
  99637. * @param edge not important for LineMesh
  99638. * @param faceNormals not important for LineMesh
  99639. * @param p0 beginnig of line
  99640. * @param p1 end of line
  99641. */
  99642. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  99643. var offset = this._linesPositions.length / 3;
  99644. var normal = p0.subtract(p1);
  99645. normal.normalize();
  99646. // Positions
  99647. this._linesPositions.push(p0.x);
  99648. this._linesPositions.push(p0.y);
  99649. this._linesPositions.push(p0.z);
  99650. this._linesPositions.push(p0.x);
  99651. this._linesPositions.push(p0.y);
  99652. this._linesPositions.push(p0.z);
  99653. this._linesPositions.push(p1.x);
  99654. this._linesPositions.push(p1.y);
  99655. this._linesPositions.push(p1.z);
  99656. this._linesPositions.push(p1.x);
  99657. this._linesPositions.push(p1.y);
  99658. this._linesPositions.push(p1.z);
  99659. // Normals
  99660. this._linesNormals.push(p1.x);
  99661. this._linesNormals.push(p1.y);
  99662. this._linesNormals.push(p1.z);
  99663. this._linesNormals.push(-1);
  99664. this._linesNormals.push(p1.x);
  99665. this._linesNormals.push(p1.y);
  99666. this._linesNormals.push(p1.z);
  99667. this._linesNormals.push(1);
  99668. this._linesNormals.push(p0.x);
  99669. this._linesNormals.push(p0.y);
  99670. this._linesNormals.push(p0.z);
  99671. this._linesNormals.push(-1);
  99672. this._linesNormals.push(p0.x);
  99673. this._linesNormals.push(p0.y);
  99674. this._linesNormals.push(p0.z);
  99675. this._linesNormals.push(1);
  99676. // Indices
  99677. this._linesIndices.push(offset);
  99678. this._linesIndices.push(offset + 1);
  99679. this._linesIndices.push(offset + 2);
  99680. this._linesIndices.push(offset);
  99681. this._linesIndices.push(offset + 2);
  99682. this._linesIndices.push(offset + 3);
  99683. };
  99684. /**
  99685. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  99686. */
  99687. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  99688. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99689. var indices = this._source.getIndices();
  99690. if (!indices || !positions) {
  99691. return;
  99692. }
  99693. // First let's find adjacencies
  99694. var adjacencies = new Array();
  99695. var faceNormals = new Array();
  99696. var index;
  99697. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  99698. var currentAdjecancy = new FaceAdjacencies();
  99699. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  99700. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  99701. adjacencies.push(currentAdjecancy);
  99702. }
  99703. // Create lines
  99704. for (index = 0; index < adjacencies.length; index++) {
  99705. // 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
  99706. var current = adjacencies[index];
  99707. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  99708. }
  99709. // Merge into a single mesh
  99710. var engine = this._source.getScene().getEngine();
  99711. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  99712. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  99713. this._ib = engine.createIndexBuffer(this._linesIndices);
  99714. this._indicesCount = this._linesIndices.length;
  99715. };
  99716. return LineEdgesRenderer;
  99717. }(BABYLON.EdgesRenderer));
  99718. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  99719. })(BABYLON || (BABYLON = {}));
  99720. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  99721. var BABYLON;
  99722. (function (BABYLON) {
  99723. // Adds the parser to the scene parsers.
  99724. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  99725. if (parsedData.effectLayers) {
  99726. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  99727. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  99728. container.effectLayers.push(effectLayer);
  99729. }
  99730. }
  99731. });
  99732. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  99733. var index = this.effectLayers.indexOf(toRemove);
  99734. if (index !== -1) {
  99735. this.effectLayers.splice(index, 1);
  99736. }
  99737. return index;
  99738. };
  99739. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  99740. this.effectLayers.push(newEffectLayer);
  99741. };
  99742. /**
  99743. * Defines the layer scene component responsible to manage any effect layers
  99744. * in a given scene.
  99745. */
  99746. var EffectLayerSceneComponent = /** @class */ (function () {
  99747. /**
  99748. * Creates a new instance of the component for the given scene
  99749. * @param scene Defines the scene to register the component in
  99750. */
  99751. function EffectLayerSceneComponent(scene) {
  99752. /**
  99753. * The component name helpfull to identify the component in the list of scene components.
  99754. */
  99755. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  99756. this._renderEffects = false;
  99757. this._needStencil = false;
  99758. this._previousStencilState = false;
  99759. this.scene = scene;
  99760. this._engine = scene.getEngine();
  99761. scene.effectLayers = new Array();
  99762. }
  99763. /**
  99764. * Registers the component in a given scene
  99765. */
  99766. EffectLayerSceneComponent.prototype.register = function () {
  99767. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  99768. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  99769. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  99770. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  99771. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  99772. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  99773. };
  99774. /**
  99775. * Rebuilds the elements related to this component in case of
  99776. * context lost for instance.
  99777. */
  99778. EffectLayerSceneComponent.prototype.rebuild = function () {
  99779. var layers = this.scene.effectLayers;
  99780. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99781. var effectLayer = layers_1[_i];
  99782. effectLayer._rebuild();
  99783. }
  99784. };
  99785. /**
  99786. * Serializes the component data to the specified json object
  99787. * @param serializationObject The object to serialize to
  99788. */
  99789. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  99790. // Effect layers
  99791. serializationObject.effectLayers = [];
  99792. var layers = this.scene.effectLayers;
  99793. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99794. var effectLayer = layers_2[_i];
  99795. if (effectLayer.serialize) {
  99796. serializationObject.effectLayers.push(effectLayer.serialize());
  99797. }
  99798. }
  99799. };
  99800. /**
  99801. * Adds all the element from the container to the scene
  99802. * @param container the container holding the elements
  99803. */
  99804. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  99805. var _this = this;
  99806. if (!container.effectLayers) {
  99807. return;
  99808. }
  99809. container.effectLayers.forEach(function (o) {
  99810. _this.scene.addEffectLayer(o);
  99811. });
  99812. };
  99813. /**
  99814. * Removes all the elements in the container from the scene
  99815. * @param container contains the elements to remove
  99816. */
  99817. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  99818. var _this = this;
  99819. if (!container.effectLayers) {
  99820. return;
  99821. }
  99822. container.effectLayers.forEach(function (o) {
  99823. _this.scene.removeEffectLayer(o);
  99824. });
  99825. };
  99826. /**
  99827. * Disposes the component and the associated ressources.
  99828. */
  99829. EffectLayerSceneComponent.prototype.dispose = function () {
  99830. var layers = this.scene.effectLayers;
  99831. while (layers.length) {
  99832. layers[0].dispose();
  99833. }
  99834. };
  99835. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  99836. var layers = this.scene.effectLayers;
  99837. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  99838. var layer = layers_3[_i];
  99839. if (!layer.hasMesh(mesh)) {
  99840. continue;
  99841. }
  99842. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  99843. var subMesh = _b[_a];
  99844. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  99845. return false;
  99846. }
  99847. }
  99848. }
  99849. return true;
  99850. };
  99851. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  99852. this._renderEffects = false;
  99853. this._needStencil = false;
  99854. var layers = this.scene.effectLayers;
  99855. if (layers && layers.length > 0) {
  99856. this._previousStencilState = this._engine.getStencilBuffer();
  99857. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  99858. var effectLayer = layers_4[_i];
  99859. if (effectLayer.shouldRender() &&
  99860. (!effectLayer.camera ||
  99861. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  99862. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  99863. this._renderEffects = true;
  99864. this._needStencil = this._needStencil || effectLayer.needStencil();
  99865. var renderTarget = effectLayer._mainTexture;
  99866. if (renderTarget._shouldRender()) {
  99867. this.scene.incrementRenderId();
  99868. renderTarget.render(false, false);
  99869. }
  99870. }
  99871. }
  99872. this.scene.incrementRenderId();
  99873. }
  99874. };
  99875. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  99876. // Activate effect Layer stencil
  99877. if (this._needStencil) {
  99878. this._engine.setStencilBuffer(true);
  99879. }
  99880. };
  99881. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  99882. // Restore effect Layer stencil
  99883. if (this._needStencil) {
  99884. this._engine.setStencilBuffer(this._previousStencilState);
  99885. }
  99886. };
  99887. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  99888. if (this._renderEffects) {
  99889. this._engine.setDepthBuffer(false);
  99890. var layers = this.scene.effectLayers;
  99891. for (var i = 0; i < layers.length; i++) {
  99892. var effectLayer = layers[i];
  99893. if (effectLayer.renderingGroupId === renderingGroupId) {
  99894. if (effectLayer.shouldRender()) {
  99895. effectLayer.render();
  99896. }
  99897. }
  99898. }
  99899. this._engine.setDepthBuffer(true);
  99900. }
  99901. };
  99902. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  99903. if (this._renderEffects) {
  99904. this._draw(-1);
  99905. }
  99906. };
  99907. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  99908. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  99909. this._draw(index);
  99910. }
  99911. };
  99912. return EffectLayerSceneComponent;
  99913. }());
  99914. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  99915. })(BABYLON || (BABYLON = {}));
  99916. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  99917. var __assign = (this && this.__assign) || function () {
  99918. __assign = Object.assign || function(t) {
  99919. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99920. s = arguments[i];
  99921. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99922. t[p] = s[p];
  99923. }
  99924. return t;
  99925. };
  99926. return __assign.apply(this, arguments);
  99927. };
  99928. var BABYLON;
  99929. (function (BABYLON) {
  99930. /**
  99931. * The effect layer Helps adding post process effect blended with the main pass.
  99932. *
  99933. * This can be for instance use to generate glow or higlight effects on the scene.
  99934. *
  99935. * The effect layer class can not be used directly and is intented to inherited from to be
  99936. * customized per effects.
  99937. */
  99938. var EffectLayer = /** @class */ (function () {
  99939. /**
  99940. * Instantiates a new effect Layer and references it in the scene.
  99941. * @param name The name of the layer
  99942. * @param scene The scene to use the layer in
  99943. */
  99944. function EffectLayer(
  99945. /** The Friendly of the effect in the scene */
  99946. name, scene) {
  99947. this._vertexBuffers = {};
  99948. this._maxSize = 0;
  99949. this._mainTextureDesiredSize = { width: 0, height: 0 };
  99950. this._shouldRender = true;
  99951. this._postProcesses = [];
  99952. this._textures = [];
  99953. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  99954. /**
  99955. * The clear color of the texture used to generate the glow map.
  99956. */
  99957. this.neutralColor = new BABYLON.Color4();
  99958. /**
  99959. * Specifies wether the highlight layer is enabled or not.
  99960. */
  99961. this.isEnabled = true;
  99962. /**
  99963. * An event triggered when the effect layer has been disposed.
  99964. */
  99965. this.onDisposeObservable = new BABYLON.Observable();
  99966. /**
  99967. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  99968. */
  99969. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  99970. /**
  99971. * An event triggered when the generated texture is being merged in the scene.
  99972. */
  99973. this.onBeforeComposeObservable = new BABYLON.Observable();
  99974. /**
  99975. * An event triggered when the generated texture has been merged in the scene.
  99976. */
  99977. this.onAfterComposeObservable = new BABYLON.Observable();
  99978. /**
  99979. * An event triggered when the efffect layer changes its size.
  99980. */
  99981. this.onSizeChangedObservable = new BABYLON.Observable();
  99982. this.name = name;
  99983. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  99984. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  99985. if (!component) {
  99986. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  99987. this._scene._addComponent(component);
  99988. }
  99989. this._engine = this._scene.getEngine();
  99990. this._maxSize = this._engine.getCaps().maxTextureSize;
  99991. this._scene.effectLayers.push(this);
  99992. // Generate Buffers
  99993. this._generateIndexBuffer();
  99994. this._genrateVertexBuffer();
  99995. }
  99996. Object.defineProperty(EffectLayer.prototype, "camera", {
  99997. /**
  99998. * Gets the camera attached to the layer.
  99999. */
  100000. get: function () {
  100001. return this._effectLayerOptions.camera;
  100002. },
  100003. enumerable: true,
  100004. configurable: true
  100005. });
  100006. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  100007. /**
  100008. * Gets the rendering group id the layer should render in.
  100009. */
  100010. get: function () {
  100011. return this._effectLayerOptions.renderingGroupId;
  100012. },
  100013. enumerable: true,
  100014. configurable: true
  100015. });
  100016. /**
  100017. * Initializes the effect layer with the required options.
  100018. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  100019. */
  100020. EffectLayer.prototype._init = function (options) {
  100021. // Adapt options
  100022. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  100023. this._setMainTextureSize();
  100024. this._createMainTexture();
  100025. this._createTextureAndPostProcesses();
  100026. this._mergeEffect = this._createMergeEffect();
  100027. };
  100028. /**
  100029. * Generates the index buffer of the full screen quad blending to the main canvas.
  100030. */
  100031. EffectLayer.prototype._generateIndexBuffer = function () {
  100032. // Indices
  100033. var indices = [];
  100034. indices.push(0);
  100035. indices.push(1);
  100036. indices.push(2);
  100037. indices.push(0);
  100038. indices.push(2);
  100039. indices.push(3);
  100040. this._indexBuffer = this._engine.createIndexBuffer(indices);
  100041. };
  100042. /**
  100043. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  100044. */
  100045. EffectLayer.prototype._genrateVertexBuffer = function () {
  100046. // VBO
  100047. var vertices = [];
  100048. vertices.push(1, 1);
  100049. vertices.push(-1, 1);
  100050. vertices.push(-1, -1);
  100051. vertices.push(1, -1);
  100052. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100053. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100054. };
  100055. /**
  100056. * Sets the main texture desired size which is the closest power of two
  100057. * of the engine canvas size.
  100058. */
  100059. EffectLayer.prototype._setMainTextureSize = function () {
  100060. if (this._effectLayerOptions.mainTextureFixedSize) {
  100061. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  100062. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  100063. }
  100064. else {
  100065. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  100066. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  100067. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  100068. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  100069. }
  100070. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  100071. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  100072. };
  100073. /**
  100074. * Creates the main texture for the effect layer.
  100075. */
  100076. EffectLayer.prototype._createMainTexture = function () {
  100077. var _this = this;
  100078. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  100079. width: this._mainTextureDesiredSize.width,
  100080. height: this._mainTextureDesiredSize.height
  100081. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100082. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  100083. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100084. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100085. this._mainTexture.anisotropicFilteringLevel = 1;
  100086. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100087. this._mainTexture.renderParticles = false;
  100088. this._mainTexture.renderList = null;
  100089. this._mainTexture.ignoreCameraViewport = true;
  100090. // Custom render function
  100091. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  100092. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  100093. var index;
  100094. var engine = _this._scene.getEngine();
  100095. if (depthOnlySubMeshes.length) {
  100096. engine.setColorWrite(false);
  100097. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  100098. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  100099. }
  100100. engine.setColorWrite(true);
  100101. }
  100102. for (index = 0; index < opaqueSubMeshes.length; index++) {
  100103. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  100104. }
  100105. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  100106. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  100107. }
  100108. for (index = 0; index < transparentSubMeshes.length; index++) {
  100109. _this._renderSubMesh(transparentSubMeshes.data[index]);
  100110. }
  100111. };
  100112. this._mainTexture.onClearObservable.add(function (engine) {
  100113. engine.clear(_this.neutralColor, true, true, true);
  100114. });
  100115. };
  100116. /**
  100117. * Checks for the readiness of the element composing the layer.
  100118. * @param subMesh the mesh to check for
  100119. * @param useInstances specify wether or not to use instances to render the mesh
  100120. * @param emissiveTexture the associated emissive texture used to generate the glow
  100121. * @return true if ready otherwise, false
  100122. */
  100123. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  100124. var material = subMesh.getMaterial();
  100125. if (!material) {
  100126. return false;
  100127. }
  100128. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  100129. return false;
  100130. }
  100131. var defines = [];
  100132. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100133. var mesh = subMesh.getMesh();
  100134. var uv1 = false;
  100135. var uv2 = false;
  100136. // Alpha test
  100137. if (material && material.needAlphaTesting()) {
  100138. var alphaTexture = material.getAlphaTestTexture();
  100139. if (alphaTexture) {
  100140. defines.push("#define ALPHATEST");
  100141. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100142. alphaTexture.coordinatesIndex === 1) {
  100143. defines.push("#define DIFFUSEUV2");
  100144. uv2 = true;
  100145. }
  100146. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100147. defines.push("#define DIFFUSEUV1");
  100148. uv1 = true;
  100149. }
  100150. }
  100151. }
  100152. // Emissive
  100153. if (emissiveTexture) {
  100154. defines.push("#define EMISSIVE");
  100155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  100156. emissiveTexture.coordinatesIndex === 1) {
  100157. defines.push("#define EMISSIVEUV2");
  100158. uv2 = true;
  100159. }
  100160. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100161. defines.push("#define EMISSIVEUV1");
  100162. uv1 = true;
  100163. }
  100164. }
  100165. if (uv1) {
  100166. attribs.push(BABYLON.VertexBuffer.UVKind);
  100167. defines.push("#define UV1");
  100168. }
  100169. if (uv2) {
  100170. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100171. defines.push("#define UV2");
  100172. }
  100173. // Bones
  100174. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100175. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100176. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100177. if (mesh.numBoneInfluencers > 4) {
  100178. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100179. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100180. }
  100181. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100182. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  100183. }
  100184. else {
  100185. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100186. }
  100187. // Morph targets
  100188. var manager = mesh.morphTargetManager;
  100189. var morphInfluencers = 0;
  100190. if (manager) {
  100191. if (manager.numInfluencers > 0) {
  100192. defines.push("#define MORPHTARGETS");
  100193. morphInfluencers = manager.numInfluencers;
  100194. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  100195. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  100196. }
  100197. }
  100198. // Instances
  100199. if (useInstances) {
  100200. defines.push("#define INSTANCES");
  100201. attribs.push("world0");
  100202. attribs.push("world1");
  100203. attribs.push("world2");
  100204. attribs.push("world3");
  100205. }
  100206. // Get correct effect
  100207. var join = defines.join("\n");
  100208. if (this._cachedDefines !== join) {
  100209. this._cachedDefines = join;
  100210. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  100211. }
  100212. return this._effectLayerMapGenerationEffect.isReady();
  100213. };
  100214. /**
  100215. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  100216. */
  100217. EffectLayer.prototype.render = function () {
  100218. var currentEffect = this._mergeEffect;
  100219. // Check
  100220. if (!currentEffect.isReady())
  100221. return;
  100222. for (var i = 0; i < this._postProcesses.length; i++) {
  100223. if (!this._postProcesses[i].isReady()) {
  100224. return;
  100225. }
  100226. }
  100227. var engine = this._scene.getEngine();
  100228. this.onBeforeComposeObservable.notifyObservers(this);
  100229. // Render
  100230. engine.enableEffect(currentEffect);
  100231. engine.setState(false);
  100232. // VBOs
  100233. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100234. // Cache
  100235. var previousAlphaMode = engine.getAlphaMode();
  100236. // Go Blend.
  100237. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  100238. // Blends the map on the main canvas.
  100239. this._internalRender(currentEffect);
  100240. // Restore Alpha
  100241. engine.setAlphaMode(previousAlphaMode);
  100242. this.onAfterComposeObservable.notifyObservers(this);
  100243. // Handle size changes.
  100244. var size = this._mainTexture.getSize();
  100245. this._setMainTextureSize();
  100246. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  100247. // Recreate RTT and post processes on size change.
  100248. this.onSizeChangedObservable.notifyObservers(this);
  100249. this._disposeTextureAndPostProcesses();
  100250. this._createMainTexture();
  100251. this._createTextureAndPostProcesses();
  100252. }
  100253. };
  100254. /**
  100255. * Determine if a given mesh will be used in the current effect.
  100256. * @param mesh mesh to test
  100257. * @returns true if the mesh will be used
  100258. */
  100259. EffectLayer.prototype.hasMesh = function (mesh) {
  100260. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  100261. return true;
  100262. }
  100263. return false;
  100264. };
  100265. /**
  100266. * Returns true if the layer contains information to display, otherwise false.
  100267. * @returns true if the glow layer should be rendered
  100268. */
  100269. EffectLayer.prototype.shouldRender = function () {
  100270. return this.isEnabled && this._shouldRender;
  100271. };
  100272. /**
  100273. * Returns true if the mesh should render, otherwise false.
  100274. * @param mesh The mesh to render
  100275. * @returns true if it should render otherwise false
  100276. */
  100277. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  100278. return true;
  100279. };
  100280. /**
  100281. * Returns true if the mesh should render, otherwise false.
  100282. * @param mesh The mesh to render
  100283. * @returns true if it should render otherwise false
  100284. */
  100285. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  100286. return true;
  100287. };
  100288. /**
  100289. * Renders the submesh passed in parameter to the generation map.
  100290. */
  100291. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  100292. var _this = this;
  100293. if (!this.shouldRender()) {
  100294. return;
  100295. }
  100296. var material = subMesh.getMaterial();
  100297. var mesh = subMesh.getRenderingMesh();
  100298. var scene = this._scene;
  100299. var engine = scene.getEngine();
  100300. if (!material) {
  100301. return;
  100302. }
  100303. // Do not block in blend mode.
  100304. if (material.needAlphaBlendingForMesh(mesh)) {
  100305. return;
  100306. }
  100307. // Culling
  100308. engine.setState(material.backFaceCulling);
  100309. // Managing instances
  100310. var batch = mesh._getInstancesRenderList(subMesh._id);
  100311. if (batch.mustReturn) {
  100312. return;
  100313. }
  100314. // Early Exit per mesh
  100315. if (!this._shouldRenderMesh(mesh)) {
  100316. return;
  100317. }
  100318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100319. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  100320. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  100321. engine.enableEffect(this._effectLayerMapGenerationEffect);
  100322. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  100323. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  100324. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  100325. // Alpha test
  100326. if (material && material.needAlphaTesting()) {
  100327. var alphaTexture = material.getAlphaTestTexture();
  100328. if (alphaTexture) {
  100329. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  100330. var textureMatrix = alphaTexture.getTextureMatrix();
  100331. if (textureMatrix) {
  100332. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  100333. }
  100334. }
  100335. }
  100336. // Glow emissive only
  100337. if (this._emissiveTextureAndColor.texture) {
  100338. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  100339. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  100340. }
  100341. // Bones
  100342. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100343. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100344. }
  100345. // Morph targets
  100346. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  100347. // Draw
  100348. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  100349. }
  100350. else {
  100351. // Need to reset refresh rate of the main map
  100352. this._mainTexture.resetRefreshCounter();
  100353. }
  100354. };
  100355. /**
  100356. * Rebuild the required buffers.
  100357. * @hidden Internal use only.
  100358. */
  100359. EffectLayer.prototype._rebuild = function () {
  100360. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100361. if (vb) {
  100362. vb._rebuild();
  100363. }
  100364. this._generateIndexBuffer();
  100365. };
  100366. /**
  100367. * Dispose only the render target textures and post process.
  100368. */
  100369. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  100370. this._mainTexture.dispose();
  100371. for (var i = 0; i < this._postProcesses.length; i++) {
  100372. if (this._postProcesses[i]) {
  100373. this._postProcesses[i].dispose();
  100374. }
  100375. }
  100376. this._postProcesses = [];
  100377. for (var i = 0; i < this._textures.length; i++) {
  100378. if (this._textures[i]) {
  100379. this._textures[i].dispose();
  100380. }
  100381. }
  100382. this._textures = [];
  100383. };
  100384. /**
  100385. * Dispose the highlight layer and free resources.
  100386. */
  100387. EffectLayer.prototype.dispose = function () {
  100388. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100389. if (vertexBuffer) {
  100390. vertexBuffer.dispose();
  100391. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100392. }
  100393. if (this._indexBuffer) {
  100394. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100395. this._indexBuffer = null;
  100396. }
  100397. // Clean textures and post processes
  100398. this._disposeTextureAndPostProcesses();
  100399. // Remove from scene
  100400. var index = this._scene.effectLayers.indexOf(this, 0);
  100401. if (index > -1) {
  100402. this._scene.effectLayers.splice(index, 1);
  100403. }
  100404. // Callback
  100405. this.onDisposeObservable.notifyObservers(this);
  100406. this.onDisposeObservable.clear();
  100407. this.onBeforeRenderMainTextureObservable.clear();
  100408. this.onBeforeComposeObservable.clear();
  100409. this.onAfterComposeObservable.clear();
  100410. this.onSizeChangedObservable.clear();
  100411. };
  100412. /**
  100413. * Gets the class name of the effect layer
  100414. * @returns the string with the class name of the effect layer
  100415. */
  100416. EffectLayer.prototype.getClassName = function () {
  100417. return "EffectLayer";
  100418. };
  100419. /**
  100420. * Creates an effect layer from parsed effect layer data
  100421. * @param parsedEffectLayer defines effect layer data
  100422. * @param scene defines the current scene
  100423. * @param rootUrl defines the root URL containing the effect layer information
  100424. * @returns a parsed effect Layer
  100425. */
  100426. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  100427. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  100428. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  100429. };
  100430. __decorate([
  100431. BABYLON.serialize()
  100432. ], EffectLayer.prototype, "name", void 0);
  100433. __decorate([
  100434. BABYLON.serializeAsColor4()
  100435. ], EffectLayer.prototype, "neutralColor", void 0);
  100436. __decorate([
  100437. BABYLON.serialize()
  100438. ], EffectLayer.prototype, "isEnabled", void 0);
  100439. __decorate([
  100440. BABYLON.serializeAsCameraReference()
  100441. ], EffectLayer.prototype, "camera", null);
  100442. __decorate([
  100443. BABYLON.serialize()
  100444. ], EffectLayer.prototype, "renderingGroupId", null);
  100445. return EffectLayer;
  100446. }());
  100447. BABYLON.EffectLayer = EffectLayer;
  100448. })(BABYLON || (BABYLON = {}));
  100449. //# sourceMappingURL=babylon.effectLayer.js.map
  100450. var BABYLON;
  100451. (function (BABYLON) {
  100452. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  100453. for (var index = 0; index < this.effectLayers.length; index++) {
  100454. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  100455. return this.effectLayers[index];
  100456. }
  100457. }
  100458. return null;
  100459. };
  100460. /**
  100461. * Special Glow Blur post process only blurring the alpha channel
  100462. * It enforces keeping the most luminous color in the color channel.
  100463. */
  100464. var GlowBlurPostProcess = /** @class */ (function (_super) {
  100465. __extends(GlowBlurPostProcess, _super);
  100466. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  100467. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  100468. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  100469. _this.direction = direction;
  100470. _this.kernel = kernel;
  100471. _this.onApplyObservable.add(function (effect) {
  100472. effect.setFloat2("screenSize", _this.width, _this.height);
  100473. effect.setVector2("direction", _this.direction);
  100474. effect.setFloat("blurWidth", _this.kernel);
  100475. });
  100476. return _this;
  100477. }
  100478. return GlowBlurPostProcess;
  100479. }(BABYLON.PostProcess));
  100480. /**
  100481. * The highlight layer Helps adding a glow effect around a mesh.
  100482. *
  100483. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100484. * glowy meshes to your scene.
  100485. *
  100486. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  100487. */
  100488. var HighlightLayer = /** @class */ (function (_super) {
  100489. __extends(HighlightLayer, _super);
  100490. /**
  100491. * Instantiates a new highlight Layer and references it to the scene..
  100492. * @param name The name of the layer
  100493. * @param scene The scene to use the layer in
  100494. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  100495. */
  100496. function HighlightLayer(name, scene, options) {
  100497. var _this = _super.call(this, name, scene) || this;
  100498. _this.name = name;
  100499. /**
  100500. * Specifies whether or not the inner glow is ACTIVE in the layer.
  100501. */
  100502. _this.innerGlow = true;
  100503. /**
  100504. * Specifies whether or not the outer glow is ACTIVE in the layer.
  100505. */
  100506. _this.outerGlow = true;
  100507. /**
  100508. * An event triggered when the highlight layer is being blurred.
  100509. */
  100510. _this.onBeforeBlurObservable = new BABYLON.Observable();
  100511. /**
  100512. * An event triggered when the highlight layer has been blurred.
  100513. */
  100514. _this.onAfterBlurObservable = new BABYLON.Observable();
  100515. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  100516. _this._meshes = {};
  100517. _this._excludedMeshes = {};
  100518. _this.neutralColor = HighlightLayer.NeutralColor;
  100519. // Warn on stencil
  100520. if (!_this._engine.isStencilEnable) {
  100521. 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 }");
  100522. }
  100523. // Adapt options
  100524. _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);
  100525. // Initialize the layer
  100526. _this._init({
  100527. alphaBlendingMode: _this._options.alphaBlendingMode,
  100528. camera: _this._options.camera,
  100529. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100530. mainTextureRatio: _this._options.mainTextureRatio,
  100531. renderingGroupId: _this._options.renderingGroupId
  100532. });
  100533. // Do not render as long as no meshes have been added
  100534. _this._shouldRender = false;
  100535. return _this;
  100536. }
  100537. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  100538. /**
  100539. * Gets the horizontal size of the blur.
  100540. */
  100541. get: function () {
  100542. return this._horizontalBlurPostprocess.kernel;
  100543. },
  100544. /**
  100545. * Specifies the horizontal size of the blur.
  100546. */
  100547. set: function (value) {
  100548. this._horizontalBlurPostprocess.kernel = value;
  100549. },
  100550. enumerable: true,
  100551. configurable: true
  100552. });
  100553. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  100554. /**
  100555. * Gets the vertical size of the blur.
  100556. */
  100557. get: function () {
  100558. return this._verticalBlurPostprocess.kernel;
  100559. },
  100560. /**
  100561. * Specifies the vertical size of the blur.
  100562. */
  100563. set: function (value) {
  100564. this._verticalBlurPostprocess.kernel = value;
  100565. },
  100566. enumerable: true,
  100567. configurable: true
  100568. });
  100569. /**
  100570. * Get the effect name of the layer.
  100571. * @return The effect name
  100572. */
  100573. HighlightLayer.prototype.getEffectName = function () {
  100574. return HighlightLayer.EffectName;
  100575. };
  100576. /**
  100577. * Create the merge effect. This is the shader use to blit the information back
  100578. * to the main canvas at the end of the scene rendering.
  100579. */
  100580. HighlightLayer.prototype._createMergeEffect = function () {
  100581. // Effect
  100582. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  100583. };
  100584. /**
  100585. * Creates the render target textures and post processes used in the highlight layer.
  100586. */
  100587. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  100588. var _this = this;
  100589. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  100590. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  100591. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100592. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100593. var textureType = 0;
  100594. if (this._engine.getCaps().textureHalfFloatRender) {
  100595. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100596. }
  100597. else {
  100598. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100599. }
  100600. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  100601. width: blurTextureWidth,
  100602. height: blurTextureHeight
  100603. }, this._scene, false, true, textureType);
  100604. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100605. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100606. this._blurTexture.anisotropicFilteringLevel = 16;
  100607. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  100608. this._blurTexture.renderParticles = false;
  100609. this._blurTexture.ignoreCameraViewport = true;
  100610. this._textures = [this._blurTexture];
  100611. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  100612. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100613. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  100614. effect.setTexture("textureSampler", _this._mainTexture);
  100615. });
  100616. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100617. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100618. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100619. });
  100620. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  100621. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  100622. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  100623. });
  100624. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100625. }
  100626. else {
  100627. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  100628. width: blurTextureWidth,
  100629. height: blurTextureHeight
  100630. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100631. this._horizontalBlurPostprocess.width = blurTextureWidth;
  100632. this._horizontalBlurPostprocess.height = blurTextureHeight;
  100633. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  100634. effect.setTexture("textureSampler", _this._mainTexture);
  100635. });
  100636. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  100637. width: blurTextureWidth,
  100638. height: blurTextureHeight
  100639. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100640. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  100641. }
  100642. this._mainTexture.onAfterUnbindObservable.add(function () {
  100643. _this.onBeforeBlurObservable.notifyObservers(_this);
  100644. var internalTexture = _this._blurTexture.getInternalTexture();
  100645. if (internalTexture) {
  100646. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  100647. }
  100648. _this.onAfterBlurObservable.notifyObservers(_this);
  100649. });
  100650. // Prevent autoClear.
  100651. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100652. };
  100653. /**
  100654. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100655. */
  100656. HighlightLayer.prototype.needStencil = function () {
  100657. return true;
  100658. };
  100659. /**
  100660. * Checks for the readiness of the element composing the layer.
  100661. * @param subMesh the mesh to check for
  100662. * @param useInstances specify wether or not to use instances to render the mesh
  100663. * @param emissiveTexture the associated emissive texture used to generate the glow
  100664. * @return true if ready otherwise, false
  100665. */
  100666. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  100667. var material = subMesh.getMaterial();
  100668. var mesh = subMesh.getRenderingMesh();
  100669. if (!material || !mesh || !this._meshes) {
  100670. return false;
  100671. }
  100672. var emissiveTexture = null;
  100673. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100674. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100675. emissiveTexture = material.emissiveTexture;
  100676. }
  100677. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100678. };
  100679. /**
  100680. * Implementation specific of rendering the generating effect on the main canvas.
  100681. * @param effect The effect used to render through
  100682. */
  100683. HighlightLayer.prototype._internalRender = function (effect) {
  100684. // Texture
  100685. effect.setTexture("textureSampler", this._blurTexture);
  100686. // Cache
  100687. var engine = this._engine;
  100688. var previousStencilBuffer = engine.getStencilBuffer();
  100689. var previousStencilFunction = engine.getStencilFunction();
  100690. var previousStencilMask = engine.getStencilMask();
  100691. var previousStencilOperationPass = engine.getStencilOperationPass();
  100692. var previousStencilOperationFail = engine.getStencilOperationFail();
  100693. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  100694. var previousStencilReference = engine.getStencilFunctionReference();
  100695. // Stencil operations
  100696. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  100697. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  100698. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  100699. // Draw order
  100700. engine.setStencilMask(0x00);
  100701. engine.setStencilBuffer(true);
  100702. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  100703. // 2 passes inner outer
  100704. if (this.outerGlow) {
  100705. effect.setFloat("offset", 0);
  100706. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  100707. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100708. }
  100709. if (this.innerGlow) {
  100710. effect.setFloat("offset", 1);
  100711. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  100712. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100713. }
  100714. // Restore Cache
  100715. engine.setStencilFunction(previousStencilFunction);
  100716. engine.setStencilMask(previousStencilMask);
  100717. engine.setStencilBuffer(previousStencilBuffer);
  100718. engine.setStencilOperationPass(previousStencilOperationPass);
  100719. engine.setStencilOperationFail(previousStencilOperationFail);
  100720. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  100721. engine.setStencilFunctionReference(previousStencilReference);
  100722. };
  100723. /**
  100724. * Returns true if the layer contains information to display, otherwise false.
  100725. */
  100726. HighlightLayer.prototype.shouldRender = function () {
  100727. if (_super.prototype.shouldRender.call(this)) {
  100728. return this._meshes ? true : false;
  100729. }
  100730. return false;
  100731. };
  100732. /**
  100733. * Returns true if the mesh should render, otherwise false.
  100734. * @param mesh The mesh to render
  100735. * @returns true if it should render otherwise false
  100736. */
  100737. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  100738. // Excluded Mesh
  100739. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  100740. return false;
  100741. }
  100742. ;
  100743. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100744. return false;
  100745. }
  100746. return true;
  100747. };
  100748. /**
  100749. * Sets the required values for both the emissive texture and and the main color.
  100750. */
  100751. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100752. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  100753. if (highlightLayerMesh) {
  100754. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  100755. }
  100756. else {
  100757. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100758. }
  100759. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  100760. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100761. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  100762. }
  100763. else {
  100764. this._emissiveTextureAndColor.texture = null;
  100765. }
  100766. };
  100767. /**
  100768. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  100769. * @param mesh The mesh to exclude from the highlight layer
  100770. */
  100771. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  100772. if (!this._excludedMeshes) {
  100773. return;
  100774. }
  100775. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100776. if (!meshExcluded) {
  100777. this._excludedMeshes[mesh.uniqueId] = {
  100778. mesh: mesh,
  100779. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  100780. mesh.getEngine().setStencilBuffer(false);
  100781. }),
  100782. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  100783. mesh.getEngine().setStencilBuffer(true);
  100784. }),
  100785. };
  100786. }
  100787. };
  100788. /**
  100789. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  100790. * @param mesh The mesh to highlight
  100791. */
  100792. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  100793. if (!this._excludedMeshes) {
  100794. return;
  100795. }
  100796. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  100797. if (meshExcluded) {
  100798. if (meshExcluded.beforeRender) {
  100799. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  100800. }
  100801. if (meshExcluded.afterRender) {
  100802. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  100803. }
  100804. }
  100805. this._excludedMeshes[mesh.uniqueId] = null;
  100806. };
  100807. /**
  100808. * Determine if a given mesh will be highlighted by the current HighlightLayer
  100809. * @param mesh mesh to test
  100810. * @returns true if the mesh will be highlighted by the current HighlightLayer
  100811. */
  100812. HighlightLayer.prototype.hasMesh = function (mesh) {
  100813. if (!this._meshes) {
  100814. return false;
  100815. }
  100816. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100817. return false;
  100818. }
  100819. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  100820. };
  100821. /**
  100822. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  100823. * @param mesh The mesh to highlight
  100824. * @param color The color of the highlight
  100825. * @param glowEmissiveOnly Extract the glow from the emissive texture
  100826. */
  100827. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  100828. var _this = this;
  100829. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  100830. if (!this._meshes) {
  100831. return;
  100832. }
  100833. var meshHighlight = this._meshes[mesh.uniqueId];
  100834. if (meshHighlight) {
  100835. meshHighlight.color = color;
  100836. }
  100837. else {
  100838. this._meshes[mesh.uniqueId] = {
  100839. mesh: mesh,
  100840. color: color,
  100841. // Lambda required for capture due to Observable this context
  100842. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  100843. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  100844. _this._defaultStencilReference(mesh);
  100845. }
  100846. else {
  100847. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  100848. }
  100849. }),
  100850. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  100851. glowEmissiveOnly: glowEmissiveOnly
  100852. };
  100853. mesh.onDisposeObservable.add(function () {
  100854. _this._disposeMesh(mesh);
  100855. });
  100856. }
  100857. this._shouldRender = true;
  100858. };
  100859. /**
  100860. * Remove a mesh from the highlight layer in order to make it stop glowing.
  100861. * @param mesh The mesh to highlight
  100862. */
  100863. HighlightLayer.prototype.removeMesh = function (mesh) {
  100864. if (!this._meshes) {
  100865. return;
  100866. }
  100867. var meshHighlight = this._meshes[mesh.uniqueId];
  100868. if (meshHighlight) {
  100869. if (meshHighlight.observerHighlight) {
  100870. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100871. }
  100872. if (meshHighlight.observerDefault) {
  100873. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100874. }
  100875. delete this._meshes[mesh.uniqueId];
  100876. }
  100877. this._shouldRender = false;
  100878. for (var meshHighlightToCheck in this._meshes) {
  100879. if (this._meshes[meshHighlightToCheck]) {
  100880. this._shouldRender = true;
  100881. break;
  100882. }
  100883. }
  100884. };
  100885. /**
  100886. * Force the stencil to the normal expected value for none glowing parts
  100887. */
  100888. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  100889. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  100890. };
  100891. /**
  100892. * Free any resources and references associated to a mesh.
  100893. * Internal use
  100894. * @param mesh The mesh to free.
  100895. * @hidden
  100896. */
  100897. HighlightLayer.prototype._disposeMesh = function (mesh) {
  100898. this.removeMesh(mesh);
  100899. this.removeExcludedMesh(mesh);
  100900. };
  100901. /**
  100902. * Dispose the highlight layer and free resources.
  100903. */
  100904. HighlightLayer.prototype.dispose = function () {
  100905. if (this._meshes) {
  100906. // Clean mesh references
  100907. for (var id in this._meshes) {
  100908. var meshHighlight = this._meshes[id];
  100909. if (meshHighlight && meshHighlight.mesh) {
  100910. if (meshHighlight.observerHighlight) {
  100911. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  100912. }
  100913. if (meshHighlight.observerDefault) {
  100914. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  100915. }
  100916. }
  100917. }
  100918. this._meshes = null;
  100919. }
  100920. if (this._excludedMeshes) {
  100921. for (var id in this._excludedMeshes) {
  100922. var meshHighlight = this._excludedMeshes[id];
  100923. if (meshHighlight) {
  100924. if (meshHighlight.beforeRender) {
  100925. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  100926. }
  100927. if (meshHighlight.afterRender) {
  100928. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  100929. }
  100930. }
  100931. }
  100932. this._excludedMeshes = null;
  100933. }
  100934. _super.prototype.dispose.call(this);
  100935. };
  100936. /**
  100937. * Gets the class name of the effect layer
  100938. * @returns the string with the class name of the effect layer
  100939. */
  100940. HighlightLayer.prototype.getClassName = function () {
  100941. return "HighlightLayer";
  100942. };
  100943. /**
  100944. * Serializes this Highlight layer
  100945. * @returns a serialized Highlight layer object
  100946. */
  100947. HighlightLayer.prototype.serialize = function () {
  100948. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100949. serializationObject.customType = "BABYLON.HighlightLayer";
  100950. // Highlighted meshes
  100951. serializationObject.meshes = [];
  100952. if (this._meshes) {
  100953. for (var m in this._meshes) {
  100954. var mesh = this._meshes[m];
  100955. if (mesh) {
  100956. serializationObject.meshes.push({
  100957. glowEmissiveOnly: mesh.glowEmissiveOnly,
  100958. color: mesh.color.asArray(),
  100959. meshId: mesh.mesh.id
  100960. });
  100961. }
  100962. }
  100963. }
  100964. // Excluded meshes
  100965. serializationObject.excludedMeshes = [];
  100966. if (this._excludedMeshes) {
  100967. for (var e in this._excludedMeshes) {
  100968. var excludedMesh = this._excludedMeshes[e];
  100969. if (excludedMesh) {
  100970. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  100971. }
  100972. }
  100973. }
  100974. return serializationObject;
  100975. };
  100976. /**
  100977. * Creates a Highlight layer from parsed Highlight layer data
  100978. * @param parsedHightlightLayer defines the Highlight layer data
  100979. * @param scene defines the current scene
  100980. * @param rootUrl defines the root URL containing the Highlight layer information
  100981. * @returns a parsed Highlight layer
  100982. */
  100983. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  100984. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  100985. var index;
  100986. // Excluded meshes
  100987. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  100988. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  100989. if (mesh) {
  100990. hl.addExcludedMesh(mesh);
  100991. }
  100992. }
  100993. // Included meshes
  100994. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  100995. var highlightedMesh = parsedHightlightLayer.meshes[index];
  100996. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  100997. if (mesh) {
  100998. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  100999. }
  101000. }
  101001. return hl;
  101002. };
  101003. /**
  101004. * Effect Name of the highlight layer.
  101005. */
  101006. HighlightLayer.EffectName = "HighlightLayer";
  101007. /**
  101008. * The neutral color used during the preparation of the glow effect.
  101009. * This is black by default as the blend operation is a blend operation.
  101010. */
  101011. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  101012. /**
  101013. * Stencil value used for glowing meshes.
  101014. */
  101015. HighlightLayer.GlowingMeshStencilReference = 0x02;
  101016. /**
  101017. * Stencil value used for the other meshes in the scene.
  101018. */
  101019. HighlightLayer.NormalMeshStencilReference = 0x01;
  101020. __decorate([
  101021. BABYLON.serialize()
  101022. ], HighlightLayer.prototype, "innerGlow", void 0);
  101023. __decorate([
  101024. BABYLON.serialize()
  101025. ], HighlightLayer.prototype, "outerGlow", void 0);
  101026. __decorate([
  101027. BABYLON.serialize()
  101028. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  101029. __decorate([
  101030. BABYLON.serialize()
  101031. ], HighlightLayer.prototype, "blurVerticalSize", null);
  101032. __decorate([
  101033. BABYLON.serialize("options")
  101034. ], HighlightLayer.prototype, "_options", void 0);
  101035. return HighlightLayer;
  101036. }(BABYLON.EffectLayer));
  101037. BABYLON.HighlightLayer = HighlightLayer;
  101038. })(BABYLON || (BABYLON = {}));
  101039. //# sourceMappingURL=babylon.highlightLayer.js.map
  101040. var BABYLON;
  101041. (function (BABYLON) {
  101042. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  101043. for (var index = 0; index < this.effectLayers.length; index++) {
  101044. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  101045. return this.effectLayers[index];
  101046. }
  101047. }
  101048. return null;
  101049. };
  101050. /**
  101051. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  101052. *
  101053. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  101054. * glowy meshes to your scene.
  101055. *
  101056. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  101057. */
  101058. var GlowLayer = /** @class */ (function (_super) {
  101059. __extends(GlowLayer, _super);
  101060. /**
  101061. * Instantiates a new glow Layer and references it to the scene.
  101062. * @param name The name of the layer
  101063. * @param scene The scene to use the layer in
  101064. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  101065. */
  101066. function GlowLayer(name, scene, options) {
  101067. var _this = _super.call(this, name, scene) || this;
  101068. _this._intensity = 1.0;
  101069. _this._includedOnlyMeshes = [];
  101070. _this._excludedMeshes = [];
  101071. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  101072. // Adapt options
  101073. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  101074. // Initialize the layer
  101075. _this._init({
  101076. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  101077. camera: _this._options.camera,
  101078. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  101079. mainTextureRatio: _this._options.mainTextureRatio,
  101080. renderingGroupId: _this._options.renderingGroupId
  101081. });
  101082. return _this;
  101083. }
  101084. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  101085. /**
  101086. * Gets the kernel size of the blur.
  101087. */
  101088. get: function () {
  101089. return this._horizontalBlurPostprocess1.kernel;
  101090. },
  101091. /**
  101092. * Sets the kernel size of the blur.
  101093. */
  101094. set: function (value) {
  101095. this._horizontalBlurPostprocess1.kernel = value;
  101096. this._verticalBlurPostprocess1.kernel = value;
  101097. this._horizontalBlurPostprocess2.kernel = value;
  101098. this._verticalBlurPostprocess2.kernel = value;
  101099. },
  101100. enumerable: true,
  101101. configurable: true
  101102. });
  101103. Object.defineProperty(GlowLayer.prototype, "intensity", {
  101104. /**
  101105. * Gets the glow intensity.
  101106. */
  101107. get: function () {
  101108. return this._intensity;
  101109. },
  101110. /**
  101111. * Sets the glow intensity.
  101112. */
  101113. set: function (value) {
  101114. this._intensity = value;
  101115. },
  101116. enumerable: true,
  101117. configurable: true
  101118. });
  101119. /**
  101120. * Get the effect name of the layer.
  101121. * @return The effect name
  101122. */
  101123. GlowLayer.prototype.getEffectName = function () {
  101124. return GlowLayer.EffectName;
  101125. };
  101126. /**
  101127. * Create the merge effect. This is the shader use to blit the information back
  101128. * to the main canvas at the end of the scene rendering.
  101129. */
  101130. GlowLayer.prototype._createMergeEffect = function () {
  101131. // Effect
  101132. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  101133. };
  101134. /**
  101135. * Creates the render target textures and post processes used in the glow layer.
  101136. */
  101137. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  101138. var _this = this;
  101139. var blurTextureWidth = this._mainTextureDesiredSize.width;
  101140. var blurTextureHeight = this._mainTextureDesiredSize.height;
  101141. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  101142. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  101143. var textureType = 0;
  101144. if (this._engine.getCaps().textureHalfFloatRender) {
  101145. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  101146. }
  101147. else {
  101148. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101149. }
  101150. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  101151. width: blurTextureWidth,
  101152. height: blurTextureHeight
  101153. }, this._scene, false, true, textureType);
  101154. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101155. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101156. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101157. this._blurTexture1.renderParticles = false;
  101158. this._blurTexture1.ignoreCameraViewport = true;
  101159. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  101160. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  101161. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  101162. width: blurTextureWidth2,
  101163. height: blurTextureHeight2
  101164. }, this._scene, false, true, textureType);
  101165. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101166. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101167. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101168. this._blurTexture2.renderParticles = false;
  101169. this._blurTexture2.ignoreCameraViewport = true;
  101170. this._textures = [this._blurTexture1, this._blurTexture2];
  101171. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101172. width: blurTextureWidth,
  101173. height: blurTextureHeight
  101174. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101175. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  101176. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  101177. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  101178. effect.setTexture("textureSampler", _this._mainTexture);
  101179. });
  101180. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101181. width: blurTextureWidth,
  101182. height: blurTextureHeight
  101183. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101184. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  101185. width: blurTextureWidth2,
  101186. height: blurTextureHeight2
  101187. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101188. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  101189. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  101190. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  101191. effect.setTexture("textureSampler", _this._blurTexture1);
  101192. });
  101193. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  101194. width: blurTextureWidth2,
  101195. height: blurTextureHeight2
  101196. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  101197. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101198. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  101199. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  101200. this._mainTexture.samples = this._options.mainTextureSamples;
  101201. this._mainTexture.onAfterUnbindObservable.add(function () {
  101202. var internalTexture = _this._blurTexture1.getInternalTexture();
  101203. if (internalTexture) {
  101204. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  101205. internalTexture = _this._blurTexture2.getInternalTexture();
  101206. if (internalTexture) {
  101207. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  101208. }
  101209. }
  101210. });
  101211. // Prevent autoClear.
  101212. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  101213. };
  101214. /**
  101215. * Checks for the readiness of the element composing the layer.
  101216. * @param subMesh the mesh to check for
  101217. * @param useInstances specify wether or not to use instances to render the mesh
  101218. * @param emissiveTexture the associated emissive texture used to generate the glow
  101219. * @return true if ready otherwise, false
  101220. */
  101221. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  101222. var material = subMesh.getMaterial();
  101223. var mesh = subMesh.getRenderingMesh();
  101224. if (!material || !mesh) {
  101225. return false;
  101226. }
  101227. var emissiveTexture = material.emissiveTexture;
  101228. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  101229. };
  101230. /**
  101231. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  101232. */
  101233. GlowLayer.prototype.needStencil = function () {
  101234. return false;
  101235. };
  101236. /**
  101237. * Implementation specific of rendering the generating effect on the main canvas.
  101238. * @param effect The effect used to render through
  101239. */
  101240. GlowLayer.prototype._internalRender = function (effect) {
  101241. // Texture
  101242. effect.setTexture("textureSampler", this._blurTexture1);
  101243. effect.setTexture("textureSampler2", this._blurTexture2);
  101244. effect.setFloat("offset", this._intensity);
  101245. // Cache
  101246. var engine = this._engine;
  101247. var previousStencilBuffer = engine.getStencilBuffer();
  101248. // Draw order
  101249. engine.setStencilBuffer(false);
  101250. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101251. // Draw order
  101252. engine.setStencilBuffer(previousStencilBuffer);
  101253. };
  101254. /**
  101255. * Sets the required values for both the emissive texture and and the main color.
  101256. */
  101257. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  101258. var textureLevel = 1.0;
  101259. if (this.customEmissiveTextureSelector) {
  101260. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  101261. }
  101262. else {
  101263. if (material) {
  101264. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  101265. if (this._emissiveTextureAndColor.texture) {
  101266. textureLevel = this._emissiveTextureAndColor.texture.level;
  101267. }
  101268. }
  101269. else {
  101270. this._emissiveTextureAndColor.texture = null;
  101271. }
  101272. }
  101273. if (this.customEmissiveColorSelector) {
  101274. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  101275. }
  101276. else {
  101277. if (material.emissiveColor) {
  101278. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  101279. }
  101280. else {
  101281. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  101282. }
  101283. }
  101284. };
  101285. /**
  101286. * Returns true if the mesh should render, otherwise false.
  101287. * @param mesh The mesh to render
  101288. * @returns true if it should render otherwise false
  101289. */
  101290. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  101291. return this.hasMesh(mesh);
  101292. };
  101293. /**
  101294. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  101295. * @param mesh The mesh to exclude from the glow layer
  101296. */
  101297. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  101298. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  101299. this._excludedMeshes.push(mesh.uniqueId);
  101300. }
  101301. };
  101302. /**
  101303. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  101304. * @param mesh The mesh to remove
  101305. */
  101306. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  101307. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  101308. if (index !== -1) {
  101309. this._excludedMeshes.splice(index, 1);
  101310. }
  101311. };
  101312. /**
  101313. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  101314. * @param mesh The mesh to include in the glow layer
  101315. */
  101316. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  101317. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  101318. this._includedOnlyMeshes.push(mesh.uniqueId);
  101319. }
  101320. };
  101321. /**
  101322. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  101323. * @param mesh The mesh to remove
  101324. */
  101325. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  101326. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  101327. if (index !== -1) {
  101328. this._includedOnlyMeshes.splice(index, 1);
  101329. }
  101330. };
  101331. /**
  101332. * Determine if a given mesh will be used in the glow layer
  101333. * @param mesh The mesh to test
  101334. * @returns true if the mesh will be highlighted by the current glow layer
  101335. */
  101336. GlowLayer.prototype.hasMesh = function (mesh) {
  101337. if (!_super.prototype.hasMesh.call(this, mesh)) {
  101338. return false;
  101339. }
  101340. // Included Mesh
  101341. if (this._includedOnlyMeshes.length) {
  101342. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  101343. }
  101344. ;
  101345. // Excluded Mesh
  101346. if (this._excludedMeshes.length) {
  101347. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  101348. }
  101349. ;
  101350. return true;
  101351. };
  101352. /**
  101353. * Free any resources and references associated to a mesh.
  101354. * Internal use
  101355. * @param mesh The mesh to free.
  101356. * @hidden
  101357. */
  101358. GlowLayer.prototype._disposeMesh = function (mesh) {
  101359. this.removeIncludedOnlyMesh(mesh);
  101360. this.removeExcludedMesh(mesh);
  101361. };
  101362. /**
  101363. * Gets the class name of the effect layer
  101364. * @returns the string with the class name of the effect layer
  101365. */
  101366. GlowLayer.prototype.getClassName = function () {
  101367. return "GlowLayer";
  101368. };
  101369. /**
  101370. * Serializes this glow layer
  101371. * @returns a serialized glow layer object
  101372. */
  101373. GlowLayer.prototype.serialize = function () {
  101374. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101375. serializationObject.customType = "BABYLON.GlowLayer";
  101376. var index;
  101377. // Included meshes
  101378. serializationObject.includedMeshes = [];
  101379. if (this._includedOnlyMeshes.length) {
  101380. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  101381. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  101382. if (mesh) {
  101383. serializationObject.includedMeshes.push(mesh.id);
  101384. }
  101385. }
  101386. }
  101387. // Excluded meshes
  101388. serializationObject.excludedMeshes = [];
  101389. if (this._excludedMeshes.length) {
  101390. for (index = 0; index < this._excludedMeshes.length; index++) {
  101391. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  101392. if (mesh) {
  101393. serializationObject.excludedMeshes.push(mesh.id);
  101394. }
  101395. }
  101396. }
  101397. return serializationObject;
  101398. };
  101399. /**
  101400. * Creates a Glow Layer from parsed glow layer data
  101401. * @param parsedGlowLayer defines glow layer data
  101402. * @param scene defines the current scene
  101403. * @param rootUrl defines the root URL containing the glow layer information
  101404. * @returns a parsed Glow Layer
  101405. */
  101406. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  101407. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  101408. var index;
  101409. // Excluded meshes
  101410. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  101411. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  101412. if (mesh) {
  101413. gl.addExcludedMesh(mesh);
  101414. }
  101415. }
  101416. // Included meshes
  101417. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  101418. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  101419. if (mesh) {
  101420. gl.addIncludedOnlyMesh(mesh);
  101421. }
  101422. }
  101423. return gl;
  101424. };
  101425. /**
  101426. * Effect Name of the layer.
  101427. */
  101428. GlowLayer.EffectName = "GlowLayer";
  101429. /**
  101430. * The default blur kernel size used for the glow.
  101431. */
  101432. GlowLayer.DefaultBlurKernelSize = 32;
  101433. /**
  101434. * The default texture size ratio used for the glow.
  101435. */
  101436. GlowLayer.DefaultTextureRatio = 0.5;
  101437. __decorate([
  101438. BABYLON.serialize()
  101439. ], GlowLayer.prototype, "blurKernelSize", null);
  101440. __decorate([
  101441. BABYLON.serialize()
  101442. ], GlowLayer.prototype, "intensity", null);
  101443. __decorate([
  101444. BABYLON.serialize("options")
  101445. ], GlowLayer.prototype, "_options", void 0);
  101446. return GlowLayer;
  101447. }(BABYLON.EffectLayer));
  101448. BABYLON.GlowLayer = GlowLayer;
  101449. })(BABYLON || (BABYLON = {}));
  101450. //# sourceMappingURL=babylon.glowLayer.js.map
  101451. var BABYLON;
  101452. (function (BABYLON) {
  101453. /**
  101454. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  101455. */
  101456. var AssetTaskState;
  101457. (function (AssetTaskState) {
  101458. /**
  101459. * Initialization
  101460. */
  101461. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  101462. /**
  101463. * Running
  101464. */
  101465. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  101466. /**
  101467. * Done
  101468. */
  101469. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  101470. /**
  101471. * Error
  101472. */
  101473. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  101474. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  101475. /**
  101476. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  101477. */
  101478. var AbstractAssetTask = /** @class */ (function () {
  101479. /**
  101480. * Creates a new {BABYLON.AssetsManager}
  101481. * @param name defines the name of the task
  101482. */
  101483. function AbstractAssetTask(
  101484. /**
  101485. * Task name
  101486. */ name) {
  101487. this.name = name;
  101488. this._isCompleted = false;
  101489. this._taskState = AssetTaskState.INIT;
  101490. }
  101491. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  101492. /**
  101493. * Get if the task is completed
  101494. */
  101495. get: function () {
  101496. return this._isCompleted;
  101497. },
  101498. enumerable: true,
  101499. configurable: true
  101500. });
  101501. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  101502. /**
  101503. * Gets the current state of the task
  101504. */
  101505. get: function () {
  101506. return this._taskState;
  101507. },
  101508. enumerable: true,
  101509. configurable: true
  101510. });
  101511. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  101512. /**
  101513. * Gets the current error object (if task is in error)
  101514. */
  101515. get: function () {
  101516. return this._errorObject;
  101517. },
  101518. enumerable: true,
  101519. configurable: true
  101520. });
  101521. /**
  101522. * Internal only
  101523. * @hidden
  101524. */
  101525. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  101526. if (this._errorObject) {
  101527. return;
  101528. }
  101529. this._errorObject = {
  101530. message: message,
  101531. exception: exception
  101532. };
  101533. };
  101534. /**
  101535. * Execute the current task
  101536. * @param scene defines the scene where you want your assets to be loaded
  101537. * @param onSuccess is a callback called when the task is successfully executed
  101538. * @param onError is a callback called if an error occurs
  101539. */
  101540. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101541. var _this = this;
  101542. this._taskState = AssetTaskState.RUNNING;
  101543. this.runTask(scene, function () {
  101544. _this.onDoneCallback(onSuccess, onError);
  101545. }, function (msg, exception) {
  101546. _this.onErrorCallback(onError, msg, exception);
  101547. });
  101548. };
  101549. /**
  101550. * Execute the current task
  101551. * @param scene defines the scene where you want your assets to be loaded
  101552. * @param onSuccess is a callback called when the task is successfully executed
  101553. * @param onError is a callback called if an error occurs
  101554. */
  101555. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101556. throw new Error("runTask is not implemented");
  101557. };
  101558. /**
  101559. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  101560. * This can be used with failed tasks that have the reason for failure fixed.
  101561. */
  101562. AbstractAssetTask.prototype.reset = function () {
  101563. this._taskState = AssetTaskState.INIT;
  101564. };
  101565. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  101566. this._taskState = AssetTaskState.ERROR;
  101567. this._errorObject = {
  101568. message: message,
  101569. exception: exception
  101570. };
  101571. if (this.onError) {
  101572. this.onError(this, message, exception);
  101573. }
  101574. onError();
  101575. };
  101576. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  101577. try {
  101578. this._taskState = AssetTaskState.DONE;
  101579. this._isCompleted = true;
  101580. if (this.onSuccess) {
  101581. this.onSuccess(this);
  101582. }
  101583. onSuccess();
  101584. }
  101585. catch (e) {
  101586. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  101587. }
  101588. };
  101589. return AbstractAssetTask;
  101590. }());
  101591. BABYLON.AbstractAssetTask = AbstractAssetTask;
  101592. /**
  101593. * Class used to share progress information about assets loading
  101594. */
  101595. var AssetsProgressEvent = /** @class */ (function () {
  101596. /**
  101597. * Creates a {BABYLON.AssetsProgressEvent}
  101598. * @param remainingCount defines the number of remaining tasks to process
  101599. * @param totalCount defines the total number of tasks
  101600. * @param task defines the task that was just processed
  101601. */
  101602. function AssetsProgressEvent(remainingCount, totalCount, task) {
  101603. this.remainingCount = remainingCount;
  101604. this.totalCount = totalCount;
  101605. this.task = task;
  101606. }
  101607. return AssetsProgressEvent;
  101608. }());
  101609. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  101610. /**
  101611. * Define a task used by {BABYLON.AssetsManager} to load meshes
  101612. */
  101613. var MeshAssetTask = /** @class */ (function (_super) {
  101614. __extends(MeshAssetTask, _super);
  101615. /**
  101616. * Creates a new {BABYLON.MeshAssetTask}
  101617. * @param name defines the name of the task
  101618. * @param meshesNames defines the list of mesh's names you want to load
  101619. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  101620. * @param sceneFilename defines the filename of the scene to load from
  101621. */
  101622. function MeshAssetTask(
  101623. /**
  101624. * Defines the name of the task
  101625. */
  101626. name,
  101627. /**
  101628. * Defines the list of mesh's names you want to load
  101629. */
  101630. meshesNames,
  101631. /**
  101632. * Defines the root url to use as a base to load your meshes and associated resources
  101633. */
  101634. rootUrl,
  101635. /**
  101636. * Defines the filename of the scene to load from
  101637. */
  101638. sceneFilename) {
  101639. var _this = _super.call(this, name) || this;
  101640. _this.name = name;
  101641. _this.meshesNames = meshesNames;
  101642. _this.rootUrl = rootUrl;
  101643. _this.sceneFilename = sceneFilename;
  101644. return _this;
  101645. }
  101646. /**
  101647. * Execute the current task
  101648. * @param scene defines the scene where you want your assets to be loaded
  101649. * @param onSuccess is a callback called when the task is successfully executed
  101650. * @param onError is a callback called if an error occurs
  101651. */
  101652. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101653. var _this = this;
  101654. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  101655. _this.loadedMeshes = meshes;
  101656. _this.loadedParticleSystems = particleSystems;
  101657. _this.loadedSkeletons = skeletons;
  101658. onSuccess();
  101659. }, null, function (scene, message, exception) {
  101660. onError(message, exception);
  101661. });
  101662. };
  101663. return MeshAssetTask;
  101664. }(AbstractAssetTask));
  101665. BABYLON.MeshAssetTask = MeshAssetTask;
  101666. /**
  101667. * Define a task used by {BABYLON.AssetsManager} to load text content
  101668. */
  101669. var TextFileAssetTask = /** @class */ (function (_super) {
  101670. __extends(TextFileAssetTask, _super);
  101671. /**
  101672. * Creates a new TextFileAssetTask object
  101673. * @param name defines the name of the task
  101674. * @param url defines the location of the file to load
  101675. */
  101676. function TextFileAssetTask(
  101677. /**
  101678. * Defines the name of the task
  101679. */
  101680. name,
  101681. /**
  101682. * Defines the location of the file to load
  101683. */
  101684. url) {
  101685. var _this = _super.call(this, name) || this;
  101686. _this.name = name;
  101687. _this.url = url;
  101688. return _this;
  101689. }
  101690. /**
  101691. * Execute the current task
  101692. * @param scene defines the scene where you want your assets to be loaded
  101693. * @param onSuccess is a callback called when the task is successfully executed
  101694. * @param onError is a callback called if an error occurs
  101695. */
  101696. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101697. var _this = this;
  101698. scene._loadFile(this.url, function (data) {
  101699. _this.text = data;
  101700. onSuccess();
  101701. }, undefined, false, false, function (request, exception) {
  101702. if (request) {
  101703. onError(request.status + " " + request.statusText, exception);
  101704. }
  101705. });
  101706. };
  101707. return TextFileAssetTask;
  101708. }(AbstractAssetTask));
  101709. BABYLON.TextFileAssetTask = TextFileAssetTask;
  101710. /**
  101711. * Define a task used by {BABYLON.AssetsManager} to load binary data
  101712. */
  101713. var BinaryFileAssetTask = /** @class */ (function (_super) {
  101714. __extends(BinaryFileAssetTask, _super);
  101715. /**
  101716. * Creates a new BinaryFileAssetTask object
  101717. * @param name defines the name of the new task
  101718. * @param url defines the location of the file to load
  101719. */
  101720. function BinaryFileAssetTask(
  101721. /**
  101722. * Defines the name of the task
  101723. */
  101724. name,
  101725. /**
  101726. * Defines the location of the file to load
  101727. */
  101728. url) {
  101729. var _this = _super.call(this, name) || this;
  101730. _this.name = name;
  101731. _this.url = url;
  101732. return _this;
  101733. }
  101734. /**
  101735. * Execute the current task
  101736. * @param scene defines the scene where you want your assets to be loaded
  101737. * @param onSuccess is a callback called when the task is successfully executed
  101738. * @param onError is a callback called if an error occurs
  101739. */
  101740. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101741. var _this = this;
  101742. scene._loadFile(this.url, function (data) {
  101743. _this.data = data;
  101744. onSuccess();
  101745. }, undefined, true, true, function (request, exception) {
  101746. if (request) {
  101747. onError(request.status + " " + request.statusText, exception);
  101748. }
  101749. });
  101750. };
  101751. return BinaryFileAssetTask;
  101752. }(AbstractAssetTask));
  101753. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  101754. /**
  101755. * Define a task used by {BABYLON.AssetsManager} to load images
  101756. */
  101757. var ImageAssetTask = /** @class */ (function (_super) {
  101758. __extends(ImageAssetTask, _super);
  101759. /**
  101760. * Creates a new ImageAssetTask
  101761. * @param name defines the name of the task
  101762. * @param url defines the location of the image to load
  101763. */
  101764. function ImageAssetTask(
  101765. /**
  101766. * Defines the name of the task
  101767. */
  101768. name,
  101769. /**
  101770. * Defines the location of the image to load
  101771. */
  101772. url) {
  101773. var _this = _super.call(this, name) || this;
  101774. _this.name = name;
  101775. _this.url = url;
  101776. return _this;
  101777. }
  101778. /**
  101779. * Execute the current task
  101780. * @param scene defines the scene where you want your assets to be loaded
  101781. * @param onSuccess is a callback called when the task is successfully executed
  101782. * @param onError is a callback called if an error occurs
  101783. */
  101784. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101785. var _this = this;
  101786. var img = new Image();
  101787. BABYLON.Tools.SetCorsBehavior(this.url, img);
  101788. img.onload = function () {
  101789. _this.image = img;
  101790. onSuccess();
  101791. };
  101792. img.onerror = function (err) {
  101793. onError("Error loading image", err);
  101794. };
  101795. img.src = this.url;
  101796. };
  101797. return ImageAssetTask;
  101798. }(AbstractAssetTask));
  101799. BABYLON.ImageAssetTask = ImageAssetTask;
  101800. /**
  101801. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  101802. */
  101803. var TextureAssetTask = /** @class */ (function (_super) {
  101804. __extends(TextureAssetTask, _super);
  101805. /**
  101806. * Creates a new TextureAssetTask object
  101807. * @param name defines the name of the task
  101808. * @param url defines the location of the file to load
  101809. * @param noMipmap defines if mipmap should not be generated (default is false)
  101810. * @param invertY defines if texture must be inverted on Y axis (default is false)
  101811. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101812. */
  101813. function TextureAssetTask(
  101814. /**
  101815. * Defines the name of the task
  101816. */
  101817. name,
  101818. /**
  101819. * Defines the location of the file to load
  101820. */
  101821. url,
  101822. /**
  101823. * Defines if mipmap should not be generated (default is false)
  101824. */
  101825. noMipmap,
  101826. /**
  101827. * Defines if texture must be inverted on Y axis (default is false)
  101828. */
  101829. invertY,
  101830. /**
  101831. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  101832. */
  101833. samplingMode) {
  101834. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101835. var _this = _super.call(this, name) || this;
  101836. _this.name = name;
  101837. _this.url = url;
  101838. _this.noMipmap = noMipmap;
  101839. _this.invertY = invertY;
  101840. _this.samplingMode = samplingMode;
  101841. return _this;
  101842. }
  101843. /**
  101844. * Execute the current task
  101845. * @param scene defines the scene where you want your assets to be loaded
  101846. * @param onSuccess is a callback called when the task is successfully executed
  101847. * @param onError is a callback called if an error occurs
  101848. */
  101849. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101850. var onload = function () {
  101851. onSuccess();
  101852. };
  101853. var onerror = function (message, exception) {
  101854. onError(message, exception);
  101855. };
  101856. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  101857. };
  101858. return TextureAssetTask;
  101859. }(AbstractAssetTask));
  101860. BABYLON.TextureAssetTask = TextureAssetTask;
  101861. /**
  101862. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  101863. */
  101864. var CubeTextureAssetTask = /** @class */ (function (_super) {
  101865. __extends(CubeTextureAssetTask, _super);
  101866. /**
  101867. * Creates a new CubeTextureAssetTask
  101868. * @param name defines the name of the task
  101869. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101870. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101871. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101872. * @param files defines the explicit list of files (undefined by default)
  101873. */
  101874. function CubeTextureAssetTask(
  101875. /**
  101876. * Defines the name of the task
  101877. */
  101878. name,
  101879. /**
  101880. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  101881. */
  101882. url,
  101883. /**
  101884. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  101885. */
  101886. extensions,
  101887. /**
  101888. * Defines if mipmaps should not be generated (default is false)
  101889. */
  101890. noMipmap,
  101891. /**
  101892. * Defines the explicit list of files (undefined by default)
  101893. */
  101894. files) {
  101895. var _this = _super.call(this, name) || this;
  101896. _this.name = name;
  101897. _this.url = url;
  101898. _this.extensions = extensions;
  101899. _this.noMipmap = noMipmap;
  101900. _this.files = files;
  101901. return _this;
  101902. }
  101903. /**
  101904. * Execute the current task
  101905. * @param scene defines the scene where you want your assets to be loaded
  101906. * @param onSuccess is a callback called when the task is successfully executed
  101907. * @param onError is a callback called if an error occurs
  101908. */
  101909. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  101910. var onload = function () {
  101911. onSuccess();
  101912. };
  101913. var onerror = function (message, exception) {
  101914. onError(message, exception);
  101915. };
  101916. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  101917. };
  101918. return CubeTextureAssetTask;
  101919. }(AbstractAssetTask));
  101920. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  101921. /**
  101922. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  101923. */
  101924. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  101925. __extends(HDRCubeTextureAssetTask, _super);
  101926. /**
  101927. * Creates a new HDRCubeTextureAssetTask object
  101928. * @param name defines the name of the task
  101929. * @param url defines the location of the file to load
  101930. * @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.
  101931. * @param noMipmap defines if mipmaps should not be generated (default is false)
  101932. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101933. * @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)
  101934. * @param reserved Internal use only
  101935. */
  101936. function HDRCubeTextureAssetTask(
  101937. /**
  101938. * Defines the name of the task
  101939. */
  101940. name,
  101941. /**
  101942. * Defines the location of the file to load
  101943. */
  101944. url,
  101945. /**
  101946. * Defines the desired size (the more it increases the longer the generation will be)
  101947. */
  101948. size,
  101949. /**
  101950. * Defines if mipmaps should not be generated (default is false)
  101951. */
  101952. noMipmap,
  101953. /**
  101954. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  101955. */
  101956. generateHarmonics,
  101957. /**
  101958. * 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)
  101959. */
  101960. gammaSpace,
  101961. /**
  101962. * Internal Use Only
  101963. */
  101964. reserved) {
  101965. if (noMipmap === void 0) { noMipmap = false; }
  101966. if (generateHarmonics === void 0) { generateHarmonics = true; }
  101967. if (gammaSpace === void 0) { gammaSpace = false; }
  101968. if (reserved === void 0) { reserved = false; }
  101969. var _this = _super.call(this, name) || this;
  101970. _this.name = name;
  101971. _this.url = url;
  101972. _this.size = size;
  101973. _this.noMipmap = noMipmap;
  101974. _this.generateHarmonics = generateHarmonics;
  101975. _this.gammaSpace = gammaSpace;
  101976. _this.reserved = reserved;
  101977. return _this;
  101978. }
  101979. /**
  101980. * Execute the current task
  101981. * @param scene defines the scene where you want your assets to be loaded
  101982. * @param onSuccess is a callback called when the task is successfully executed
  101983. * @param onError is a callback called if an error occurs
  101984. */
  101985. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  101986. var onload = function () {
  101987. onSuccess();
  101988. };
  101989. var onerror = function (message, exception) {
  101990. onError(message, exception);
  101991. };
  101992. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  101993. };
  101994. return HDRCubeTextureAssetTask;
  101995. }(AbstractAssetTask));
  101996. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  101997. /**
  101998. * This class can be used to easily import assets into a scene
  101999. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  102000. */
  102001. var AssetsManager = /** @class */ (function () {
  102002. /**
  102003. * Creates a new AssetsManager
  102004. * @param scene defines the scene to work on
  102005. */
  102006. function AssetsManager(scene) {
  102007. this._isLoading = false;
  102008. this._tasks = new Array();
  102009. this._waitingTasksCount = 0;
  102010. this._totalTasksCount = 0;
  102011. /**
  102012. * Observable called when all tasks are processed
  102013. */
  102014. this.onTaskSuccessObservable = new BABYLON.Observable();
  102015. /**
  102016. * Observable called when a task had an error
  102017. */
  102018. this.onTaskErrorObservable = new BABYLON.Observable();
  102019. /**
  102020. * Observable called when a task is successful
  102021. */
  102022. this.onTasksDoneObservable = new BABYLON.Observable();
  102023. /**
  102024. * Observable called when a task is done (whatever the result is)
  102025. */
  102026. this.onProgressObservable = new BABYLON.Observable();
  102027. /**
  102028. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  102029. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  102030. */
  102031. this.useDefaultLoadingScreen = true;
  102032. this._scene = scene;
  102033. }
  102034. /**
  102035. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  102036. * @param taskName defines the name of the new task
  102037. * @param meshesNames defines the name of meshes to load
  102038. * @param rootUrl defines the root url to use to locate files
  102039. * @param sceneFilename defines the filename of the scene file
  102040. * @returns a new {BABYLON.MeshAssetTask} object
  102041. */
  102042. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  102043. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  102044. this._tasks.push(task);
  102045. return task;
  102046. };
  102047. /**
  102048. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  102049. * @param taskName defines the name of the new task
  102050. * @param url defines the url of the file to load
  102051. * @returns a new {BABYLON.TextFileAssetTask} object
  102052. */
  102053. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  102054. var task = new TextFileAssetTask(taskName, url);
  102055. this._tasks.push(task);
  102056. return task;
  102057. };
  102058. /**
  102059. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  102060. * @param taskName defines the name of the new task
  102061. * @param url defines the url of the file to load
  102062. * @returns a new {BABYLON.BinaryFileAssetTask} object
  102063. */
  102064. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  102065. var task = new BinaryFileAssetTask(taskName, url);
  102066. this._tasks.push(task);
  102067. return task;
  102068. };
  102069. /**
  102070. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  102071. * @param taskName defines the name of the new task
  102072. * @param url defines the url of the file to load
  102073. * @returns a new {BABYLON.ImageAssetTask} object
  102074. */
  102075. AssetsManager.prototype.addImageTask = function (taskName, url) {
  102076. var task = new ImageAssetTask(taskName, url);
  102077. this._tasks.push(task);
  102078. return task;
  102079. };
  102080. /**
  102081. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  102082. * @param taskName defines the name of the new task
  102083. * @param url defines the url of the file to load
  102084. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102085. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  102086. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  102087. * @returns a new {BABYLON.TextureAssetTask} object
  102088. */
  102089. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  102090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  102091. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  102092. this._tasks.push(task);
  102093. return task;
  102094. };
  102095. /**
  102096. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  102097. * @param taskName defines the name of the new task
  102098. * @param url defines the url of the file to load
  102099. * @param extensions defines the extension to use to load the cube map (can be null)
  102100. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102101. * @param files defines the list of files to load (can be null)
  102102. * @returns a new {BABYLON.CubeTextureAssetTask} object
  102103. */
  102104. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  102105. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  102106. this._tasks.push(task);
  102107. return task;
  102108. };
  102109. /**
  102110. *
  102111. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  102112. * @param taskName defines the name of the new task
  102113. * @param url defines the url of the file to load
  102114. * @param size defines the size you want for the cubemap (can be null)
  102115. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  102116. * @param generateHarmonics defines if you want to automatically generate (true by default)
  102117. * @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)
  102118. * @param reserved Internal use only
  102119. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  102120. */
  102121. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  102122. if (noMipmap === void 0) { noMipmap = false; }
  102123. if (generateHarmonics === void 0) { generateHarmonics = true; }
  102124. if (gammaSpace === void 0) { gammaSpace = false; }
  102125. if (reserved === void 0) { reserved = false; }
  102126. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  102127. this._tasks.push(task);
  102128. return task;
  102129. };
  102130. /**
  102131. * Remove a task from the assets manager.
  102132. * @param task the task to remove
  102133. */
  102134. AssetsManager.prototype.removeTask = function (task) {
  102135. var index = this._tasks.indexOf(task);
  102136. if (index > -1) {
  102137. this._tasks.splice(index, 1);
  102138. }
  102139. };
  102140. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  102141. this._waitingTasksCount--;
  102142. try {
  102143. if (this.onProgress) {
  102144. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  102145. }
  102146. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  102147. }
  102148. catch (e) {
  102149. BABYLON.Tools.Error("Error running progress callbacks.");
  102150. console.log(e);
  102151. }
  102152. if (this._waitingTasksCount === 0) {
  102153. try {
  102154. if (this.onFinish) {
  102155. this.onFinish(this._tasks);
  102156. }
  102157. // Let's remove successfull tasks
  102158. var currentTasks = this._tasks.slice();
  102159. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  102160. var task = currentTasks_1[_i];
  102161. if (task.taskState === AssetTaskState.DONE) {
  102162. var index = this._tasks.indexOf(task);
  102163. if (index > -1) {
  102164. this._tasks.splice(index, 1);
  102165. }
  102166. }
  102167. }
  102168. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102169. }
  102170. catch (e) {
  102171. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  102172. console.log(e);
  102173. }
  102174. this._isLoading = false;
  102175. this._scene.getEngine().hideLoadingUI();
  102176. }
  102177. };
  102178. AssetsManager.prototype._runTask = function (task) {
  102179. var _this = this;
  102180. var done = function () {
  102181. try {
  102182. if (_this.onTaskSuccess) {
  102183. _this.onTaskSuccess(task);
  102184. }
  102185. _this.onTaskSuccessObservable.notifyObservers(task);
  102186. _this._decreaseWaitingTasksCount(task);
  102187. }
  102188. catch (e) {
  102189. error("Error executing task success callbacks", e);
  102190. }
  102191. };
  102192. var error = function (message, exception) {
  102193. task._setErrorObject(message, exception);
  102194. if (_this.onTaskError) {
  102195. _this.onTaskError(task);
  102196. }
  102197. _this.onTaskErrorObservable.notifyObservers(task);
  102198. _this._decreaseWaitingTasksCount(task);
  102199. };
  102200. task.run(this._scene, done, error);
  102201. };
  102202. /**
  102203. * Reset the {BABYLON.AssetsManager} and remove all tasks
  102204. * @return the current instance of the {BABYLON.AssetsManager}
  102205. */
  102206. AssetsManager.prototype.reset = function () {
  102207. this._isLoading = false;
  102208. this._tasks = new Array();
  102209. return this;
  102210. };
  102211. /**
  102212. * Start the loading process
  102213. * @return the current instance of the {BABYLON.AssetsManager}
  102214. */
  102215. AssetsManager.prototype.load = function () {
  102216. if (this._isLoading) {
  102217. return this;
  102218. }
  102219. this._isLoading = true;
  102220. this._waitingTasksCount = this._tasks.length;
  102221. this._totalTasksCount = this._tasks.length;
  102222. if (this._waitingTasksCount === 0) {
  102223. this._isLoading = false;
  102224. if (this.onFinish) {
  102225. this.onFinish(this._tasks);
  102226. }
  102227. this.onTasksDoneObservable.notifyObservers(this._tasks);
  102228. return this;
  102229. }
  102230. if (this.useDefaultLoadingScreen) {
  102231. this._scene.getEngine().displayLoadingUI();
  102232. }
  102233. for (var index = 0; index < this._tasks.length; index++) {
  102234. var task = this._tasks[index];
  102235. if (task.taskState === AssetTaskState.INIT) {
  102236. this._runTask(task);
  102237. }
  102238. }
  102239. return this;
  102240. };
  102241. return AssetsManager;
  102242. }());
  102243. BABYLON.AssetsManager = AssetsManager;
  102244. })(BABYLON || (BABYLON = {}));
  102245. //# sourceMappingURL=babylon.assetsManager.js.map
  102246. var BABYLON;
  102247. (function (BABYLON) {
  102248. var serializedGeometries = [];
  102249. var serializeGeometry = function (geometry, serializationGeometries) {
  102250. if (serializedGeometries[geometry.id]) {
  102251. return;
  102252. }
  102253. if (geometry.doNotSerialize) {
  102254. return;
  102255. }
  102256. if (geometry instanceof BABYLON.BoxGeometry) {
  102257. serializationGeometries.boxes.push(geometry.serialize());
  102258. }
  102259. else if (geometry instanceof BABYLON.SphereGeometry) {
  102260. serializationGeometries.spheres.push(geometry.serialize());
  102261. }
  102262. else if (geometry instanceof BABYLON.CylinderGeometry) {
  102263. serializationGeometries.cylinders.push(geometry.serialize());
  102264. }
  102265. else if (geometry instanceof BABYLON.TorusGeometry) {
  102266. serializationGeometries.toruses.push(geometry.serialize());
  102267. }
  102268. else if (geometry instanceof BABYLON.GroundGeometry) {
  102269. serializationGeometries.grounds.push(geometry.serialize());
  102270. }
  102271. else if (geometry instanceof BABYLON.Plane) {
  102272. serializationGeometries.planes.push(geometry.serialize());
  102273. }
  102274. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  102275. serializationGeometries.torusKnots.push(geometry.serialize());
  102276. }
  102277. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  102278. throw new Error("Unknown primitive type");
  102279. }
  102280. else {
  102281. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  102282. }
  102283. serializedGeometries[geometry.id] = true;
  102284. };
  102285. var serializeMesh = function (mesh, serializationScene) {
  102286. var serializationObject = {};
  102287. // Geometry
  102288. var geometry = mesh._geometry;
  102289. if (geometry) {
  102290. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  102291. // 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
  102292. serializeGeometry(geometry, serializationScene.geometries);
  102293. }
  102294. }
  102295. // Custom
  102296. if (mesh.serialize) {
  102297. mesh.serialize(serializationObject);
  102298. }
  102299. return serializationObject;
  102300. };
  102301. var finalizeSingleMesh = function (mesh, serializationObject) {
  102302. //only works if the mesh is already loaded
  102303. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102304. //serialize material
  102305. if (mesh.material) {
  102306. if (mesh.material instanceof BABYLON.MultiMaterial) {
  102307. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  102308. serializationObject.materials = serializationObject.materials || [];
  102309. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102310. serializationObject.multiMaterials.push(mesh.material.serialize());
  102311. var _loop_1 = function (submaterial) {
  102312. if (submaterial) {
  102313. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  102314. serializationObject.materials.push(submaterial.serialize());
  102315. }
  102316. }
  102317. };
  102318. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  102319. var submaterial = _a[_i];
  102320. _loop_1(submaterial);
  102321. }
  102322. }
  102323. }
  102324. else {
  102325. serializationObject.materials = serializationObject.materials || [];
  102326. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  102327. serializationObject.materials.push(mesh.material.serialize());
  102328. }
  102329. }
  102330. }
  102331. //serialize geometry
  102332. var geometry = mesh._geometry;
  102333. if (geometry) {
  102334. if (!serializationObject.geometries) {
  102335. serializationObject.geometries = {};
  102336. serializationObject.geometries.boxes = [];
  102337. serializationObject.geometries.spheres = [];
  102338. serializationObject.geometries.cylinders = [];
  102339. serializationObject.geometries.toruses = [];
  102340. serializationObject.geometries.grounds = [];
  102341. serializationObject.geometries.planes = [];
  102342. serializationObject.geometries.torusKnots = [];
  102343. serializationObject.geometries.vertexData = [];
  102344. }
  102345. serializeGeometry(geometry, serializationObject.geometries);
  102346. }
  102347. // Skeletons
  102348. if (mesh.skeleton) {
  102349. serializationObject.skeletons = serializationObject.skeletons || [];
  102350. serializationObject.skeletons.push(mesh.skeleton.serialize());
  102351. }
  102352. //serialize the actual mesh
  102353. serializationObject.meshes = serializationObject.meshes || [];
  102354. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102355. }
  102356. };
  102357. var SceneSerializer = /** @class */ (function () {
  102358. function SceneSerializer() {
  102359. }
  102360. SceneSerializer.ClearCache = function () {
  102361. serializedGeometries = [];
  102362. };
  102363. SceneSerializer.Serialize = function (scene) {
  102364. var serializationObject = {};
  102365. SceneSerializer.ClearCache();
  102366. // Scene
  102367. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  102368. serializationObject.autoClear = scene.autoClear;
  102369. serializationObject.clearColor = scene.clearColor.asArray();
  102370. serializationObject.ambientColor = scene.ambientColor.asArray();
  102371. serializationObject.gravity = scene.gravity.asArray();
  102372. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  102373. serializationObject.workerCollisions = scene.workerCollisions;
  102374. // Fog
  102375. if (scene.fogMode && scene.fogMode !== 0) {
  102376. serializationObject.fogMode = scene.fogMode;
  102377. serializationObject.fogColor = scene.fogColor.asArray();
  102378. serializationObject.fogStart = scene.fogStart;
  102379. serializationObject.fogEnd = scene.fogEnd;
  102380. serializationObject.fogDensity = scene.fogDensity;
  102381. }
  102382. //Physics
  102383. if (scene.isPhysicsEnabled()) {
  102384. var physicEngine = scene.getPhysicsEngine();
  102385. if (physicEngine) {
  102386. serializationObject.physicsEnabled = true;
  102387. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  102388. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  102389. }
  102390. }
  102391. // Metadata
  102392. if (scene.metadata) {
  102393. serializationObject.metadata = scene.metadata;
  102394. }
  102395. // Morph targets
  102396. serializationObject.morphTargetManagers = [];
  102397. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  102398. var abstractMesh = _a[_i];
  102399. var manager = abstractMesh.morphTargetManager;
  102400. if (manager) {
  102401. serializationObject.morphTargetManagers.push(manager.serialize());
  102402. }
  102403. }
  102404. // Lights
  102405. serializationObject.lights = [];
  102406. var index;
  102407. var light;
  102408. for (index = 0; index < scene.lights.length; index++) {
  102409. light = scene.lights[index];
  102410. if (!light.doNotSerialize) {
  102411. serializationObject.lights.push(light.serialize());
  102412. }
  102413. }
  102414. // Cameras
  102415. serializationObject.cameras = [];
  102416. for (index = 0; index < scene.cameras.length; index++) {
  102417. var camera = scene.cameras[index];
  102418. if (!camera.doNotSerialize) {
  102419. serializationObject.cameras.push(camera.serialize());
  102420. }
  102421. }
  102422. if (scene.activeCamera) {
  102423. serializationObject.activeCameraID = scene.activeCamera.id;
  102424. }
  102425. // Animations
  102426. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  102427. // Materials
  102428. serializationObject.materials = [];
  102429. serializationObject.multiMaterials = [];
  102430. var material;
  102431. for (index = 0; index < scene.materials.length; index++) {
  102432. material = scene.materials[index];
  102433. if (!material.doNotSerialize) {
  102434. serializationObject.materials.push(material.serialize());
  102435. }
  102436. }
  102437. // MultiMaterials
  102438. serializationObject.multiMaterials = [];
  102439. for (index = 0; index < scene.multiMaterials.length; index++) {
  102440. var multiMaterial = scene.multiMaterials[index];
  102441. serializationObject.multiMaterials.push(multiMaterial.serialize());
  102442. }
  102443. // Environment texture
  102444. if (scene.environmentTexture) {
  102445. serializationObject.environmentTexture = scene.environmentTexture.name;
  102446. }
  102447. // Skeletons
  102448. serializationObject.skeletons = [];
  102449. for (index = 0; index < scene.skeletons.length; index++) {
  102450. var skeleton = scene.skeletons[index];
  102451. if (!skeleton.doNotSerialize) {
  102452. serializationObject.skeletons.push(skeleton.serialize());
  102453. }
  102454. }
  102455. // Transform nodes
  102456. serializationObject.transformNodes = [];
  102457. for (index = 0; index < scene.transformNodes.length; index++) {
  102458. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  102459. }
  102460. // Geometries
  102461. serializationObject.geometries = {};
  102462. serializationObject.geometries.boxes = [];
  102463. serializationObject.geometries.spheres = [];
  102464. serializationObject.geometries.cylinders = [];
  102465. serializationObject.geometries.toruses = [];
  102466. serializationObject.geometries.grounds = [];
  102467. serializationObject.geometries.planes = [];
  102468. serializationObject.geometries.torusKnots = [];
  102469. serializationObject.geometries.vertexData = [];
  102470. serializedGeometries = [];
  102471. var geometries = scene.getGeometries();
  102472. for (index = 0; index < geometries.length; index++) {
  102473. var geometry = geometries[index];
  102474. if (geometry.isReady()) {
  102475. serializeGeometry(geometry, serializationObject.geometries);
  102476. }
  102477. }
  102478. // Meshes
  102479. serializationObject.meshes = [];
  102480. for (index = 0; index < scene.meshes.length; index++) {
  102481. var abstractMesh = scene.meshes[index];
  102482. if (abstractMesh instanceof BABYLON.Mesh) {
  102483. var mesh = abstractMesh;
  102484. if (!mesh.doNotSerialize) {
  102485. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  102486. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  102487. }
  102488. }
  102489. }
  102490. }
  102491. // Particles Systems
  102492. serializationObject.particleSystems = [];
  102493. for (index = 0; index < scene.particleSystems.length; index++) {
  102494. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  102495. }
  102496. // Shadows
  102497. serializationObject.shadowGenerators = [];
  102498. for (index = 0; index < scene.lights.length; index++) {
  102499. light = scene.lights[index];
  102500. var shadowGenerator = light.getShadowGenerator();
  102501. if (shadowGenerator) {
  102502. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  102503. }
  102504. }
  102505. // Action Manager
  102506. if (scene.actionManager) {
  102507. serializationObject.actions = scene.actionManager.serialize("scene");
  102508. }
  102509. // Audio
  102510. serializationObject.sounds = [];
  102511. for (index = 0; index < scene.soundTracks.length; index++) {
  102512. var soundtrack = scene.soundTracks[index];
  102513. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  102514. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  102515. }
  102516. }
  102517. // Components
  102518. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  102519. var component = _c[_b];
  102520. component.serialize(serializationObject);
  102521. }
  102522. return serializationObject;
  102523. };
  102524. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  102525. if (withParents === void 0) { withParents = false; }
  102526. if (withChildren === void 0) { withChildren = false; }
  102527. var serializationObject = {};
  102528. SceneSerializer.ClearCache();
  102529. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  102530. if (withParents || withChildren) {
  102531. //deliberate for loop! not for each, appended should be processed as well.
  102532. for (var i = 0; i < toSerialize.length; ++i) {
  102533. if (withChildren) {
  102534. toSerialize[i].getDescendants().forEach(function (node) {
  102535. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  102536. toSerialize.push(node);
  102537. }
  102538. });
  102539. }
  102540. //make sure the array doesn't contain the object already
  102541. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  102542. toSerialize.push(toSerialize[i].parent);
  102543. }
  102544. }
  102545. }
  102546. toSerialize.forEach(function (mesh) {
  102547. finalizeSingleMesh(mesh, serializationObject);
  102548. });
  102549. return serializationObject;
  102550. };
  102551. return SceneSerializer;
  102552. }());
  102553. BABYLON.SceneSerializer = SceneSerializer;
  102554. })(BABYLON || (BABYLON = {}));
  102555. //# sourceMappingURL=babylon.sceneSerializer.js.map
  102556. var BABYLON;
  102557. (function (BABYLON) {
  102558. /**
  102559. * Class used to generate realtime reflection / refraction cube textures
  102560. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  102561. */
  102562. var ReflectionProbe = /** @class */ (function () {
  102563. /**
  102564. * Creates a new reflection probe
  102565. * @param name defines the name of the probe
  102566. * @param size defines the texture resolution (for each face)
  102567. * @param scene defines the hosting scene
  102568. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  102569. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  102570. */
  102571. function ReflectionProbe(
  102572. /** defines the name of the probe */
  102573. name, size, scene, generateMipMaps, useFloat) {
  102574. if (generateMipMaps === void 0) { generateMipMaps = true; }
  102575. if (useFloat === void 0) { useFloat = false; }
  102576. var _this = this;
  102577. this.name = name;
  102578. this._viewMatrix = BABYLON.Matrix.Identity();
  102579. this._target = BABYLON.Vector3.Zero();
  102580. this._add = BABYLON.Vector3.Zero();
  102581. this._invertYAxis = false;
  102582. /** Gets or sets probe position (center of the cube map) */
  102583. this.position = BABYLON.Vector3.Zero();
  102584. this._scene = scene;
  102585. this._scene.reflectionProbes.push(this);
  102586. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  102587. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  102588. switch (faceIndex) {
  102589. case 0:
  102590. _this._add.copyFromFloats(1, 0, 0);
  102591. break;
  102592. case 1:
  102593. _this._add.copyFromFloats(-1, 0, 0);
  102594. break;
  102595. case 2:
  102596. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  102597. break;
  102598. case 3:
  102599. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  102600. break;
  102601. case 4:
  102602. _this._add.copyFromFloats(0, 0, 1);
  102603. break;
  102604. case 5:
  102605. _this._add.copyFromFloats(0, 0, -1);
  102606. break;
  102607. }
  102608. if (_this._attachedMesh) {
  102609. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  102610. }
  102611. _this.position.addToRef(_this._add, _this._target);
  102612. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  102613. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  102614. scene._forcedViewPosition = _this.position;
  102615. });
  102616. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  102617. scene._forcedViewPosition = null;
  102618. scene.updateTransformMatrix(true);
  102619. });
  102620. if (scene.activeCamera) {
  102621. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  102622. }
  102623. }
  102624. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  102625. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  102626. get: function () {
  102627. return this._renderTargetTexture.samples;
  102628. },
  102629. set: function (value) {
  102630. this._renderTargetTexture.samples = value;
  102631. },
  102632. enumerable: true,
  102633. configurable: true
  102634. });
  102635. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  102636. /** Gets or sets the refresh rate to use (on every frame by default) */
  102637. get: function () {
  102638. return this._renderTargetTexture.refreshRate;
  102639. },
  102640. set: function (value) {
  102641. this._renderTargetTexture.refreshRate = value;
  102642. },
  102643. enumerable: true,
  102644. configurable: true
  102645. });
  102646. /**
  102647. * Gets the hosting scene
  102648. * @returns a Scene
  102649. */
  102650. ReflectionProbe.prototype.getScene = function () {
  102651. return this._scene;
  102652. };
  102653. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  102654. /** Gets the internal CubeTexture used to render to */
  102655. get: function () {
  102656. return this._renderTargetTexture;
  102657. },
  102658. enumerable: true,
  102659. configurable: true
  102660. });
  102661. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  102662. /** Gets the list of meshes to render */
  102663. get: function () {
  102664. return this._renderTargetTexture.renderList;
  102665. },
  102666. enumerable: true,
  102667. configurable: true
  102668. });
  102669. /**
  102670. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  102671. * @param mesh defines the mesh to attach to
  102672. */
  102673. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  102674. this._attachedMesh = mesh;
  102675. };
  102676. /**
  102677. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  102678. * @param renderingGroupId The rendering group id corresponding to its index
  102679. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  102680. */
  102681. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  102682. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  102683. };
  102684. /**
  102685. * Clean all associated resources
  102686. */
  102687. ReflectionProbe.prototype.dispose = function () {
  102688. var index = this._scene.reflectionProbes.indexOf(this);
  102689. if (index !== -1) {
  102690. // Remove from the scene if found
  102691. this._scene.reflectionProbes.splice(index, 1);
  102692. }
  102693. if (this._renderTargetTexture) {
  102694. this._renderTargetTexture.dispose();
  102695. this._renderTargetTexture = null;
  102696. }
  102697. };
  102698. return ReflectionProbe;
  102699. }());
  102700. BABYLON.ReflectionProbe = ReflectionProbe;
  102701. })(BABYLON || (BABYLON = {}));
  102702. //# sourceMappingURL=babylon.reflectionProbe.js.map
  102703. var BABYLON;
  102704. (function (BABYLON) {
  102705. /**
  102706. * Defines the layer scene component responsible to manage any layers
  102707. * in a given scene.
  102708. */
  102709. var LayerSceneComponent = /** @class */ (function () {
  102710. /**
  102711. * Creates a new instance of the component for the given scene
  102712. * @param scene Defines the scene to register the component in
  102713. */
  102714. function LayerSceneComponent(scene) {
  102715. /**
  102716. * The component name helpfull to identify the component in the list of scene components.
  102717. */
  102718. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  102719. this.scene = scene;
  102720. this._engine = scene.getEngine();
  102721. scene.layers = new Array();
  102722. }
  102723. /**
  102724. * Registers the component in a given scene
  102725. */
  102726. LayerSceneComponent.prototype.register = function () {
  102727. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  102728. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  102729. };
  102730. /**
  102731. * Rebuilds the elements related to this component in case of
  102732. * context lost for instance.
  102733. */
  102734. LayerSceneComponent.prototype.rebuild = function () {
  102735. var layers = this.scene.layers;
  102736. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  102737. var layer = layers_1[_i];
  102738. layer._rebuild();
  102739. }
  102740. };
  102741. /**
  102742. * Disposes the component and the associated ressources.
  102743. */
  102744. LayerSceneComponent.prototype.dispose = function () {
  102745. var layers = this.scene.layers;
  102746. while (layers.length) {
  102747. layers[0].dispose();
  102748. }
  102749. };
  102750. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  102751. var layers = this.scene.layers;
  102752. if (layers.length) {
  102753. this._engine.setDepthBuffer(false);
  102754. var cameraLayerMask = camera.layerMask;
  102755. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  102756. var layer = layers_2[_i];
  102757. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  102758. layer.render();
  102759. }
  102760. }
  102761. this._engine.setDepthBuffer(true);
  102762. }
  102763. };
  102764. LayerSceneComponent.prototype._drawBackground = function (camera) {
  102765. this._draw(camera, true);
  102766. };
  102767. LayerSceneComponent.prototype._drawForeground = function (camera) {
  102768. this._draw(camera, false);
  102769. };
  102770. return LayerSceneComponent;
  102771. }());
  102772. BABYLON.LayerSceneComponent = LayerSceneComponent;
  102773. })(BABYLON || (BABYLON = {}));
  102774. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  102775. var BABYLON;
  102776. (function (BABYLON) {
  102777. var Layer = /** @class */ (function () {
  102778. function Layer(name, imgUrl, scene, isBackground, color) {
  102779. this.name = name;
  102780. this.scale = new BABYLON.Vector2(1, 1);
  102781. this.offset = new BABYLON.Vector2(0, 0);
  102782. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  102783. this.layerMask = 0x0FFFFFFF;
  102784. this._vertexBuffers = {};
  102785. // Events
  102786. /**
  102787. * An event triggered when the layer is disposed.
  102788. */
  102789. this.onDisposeObservable = new BABYLON.Observable();
  102790. /**
  102791. * An event triggered before rendering the scene
  102792. */
  102793. this.onBeforeRenderObservable = new BABYLON.Observable();
  102794. /**
  102795. * An event triggered after rendering the scene
  102796. */
  102797. this.onAfterRenderObservable = new BABYLON.Observable();
  102798. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  102799. this.isBackground = isBackground === undefined ? true : isBackground;
  102800. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  102801. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  102802. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  102803. if (!layerComponent) {
  102804. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  102805. this._scene._addComponent(layerComponent);
  102806. }
  102807. this._scene.layers.push(this);
  102808. var engine = this._scene.getEngine();
  102809. // VBO
  102810. var vertices = [];
  102811. vertices.push(1, 1);
  102812. vertices.push(-1, 1);
  102813. vertices.push(-1, -1);
  102814. vertices.push(1, -1);
  102815. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  102816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  102817. this._createIndexBuffer();
  102818. // Effects
  102819. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  102820. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  102821. }
  102822. Object.defineProperty(Layer.prototype, "onDispose", {
  102823. set: function (callback) {
  102824. if (this._onDisposeObserver) {
  102825. this.onDisposeObservable.remove(this._onDisposeObserver);
  102826. }
  102827. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  102828. },
  102829. enumerable: true,
  102830. configurable: true
  102831. });
  102832. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  102833. set: function (callback) {
  102834. if (this._onBeforeRenderObserver) {
  102835. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  102836. }
  102837. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  102838. },
  102839. enumerable: true,
  102840. configurable: true
  102841. });
  102842. Object.defineProperty(Layer.prototype, "onAfterRender", {
  102843. set: function (callback) {
  102844. if (this._onAfterRenderObserver) {
  102845. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102846. }
  102847. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  102848. },
  102849. enumerable: true,
  102850. configurable: true
  102851. });
  102852. Layer.prototype._createIndexBuffer = function () {
  102853. var engine = this._scene.getEngine();
  102854. // Indices
  102855. var indices = [];
  102856. indices.push(0);
  102857. indices.push(1);
  102858. indices.push(2);
  102859. indices.push(0);
  102860. indices.push(2);
  102861. indices.push(3);
  102862. this._indexBuffer = engine.createIndexBuffer(indices);
  102863. };
  102864. /** @hidden */
  102865. Layer.prototype._rebuild = function () {
  102866. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102867. if (vb) {
  102868. vb._rebuild();
  102869. }
  102870. this._createIndexBuffer();
  102871. };
  102872. Layer.prototype.render = function () {
  102873. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  102874. // Check
  102875. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  102876. return;
  102877. var engine = this._scene.getEngine();
  102878. this.onBeforeRenderObservable.notifyObservers(this);
  102879. // Render
  102880. engine.enableEffect(currentEffect);
  102881. engine.setState(false);
  102882. // Texture
  102883. currentEffect.setTexture("textureSampler", this.texture);
  102884. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  102885. // Color
  102886. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  102887. // Scale / offset
  102888. currentEffect.setVector2("offset", this.offset);
  102889. currentEffect.setVector2("scale", this.scale);
  102890. // VBOs
  102891. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  102892. // Draw order
  102893. if (!this.alphaTest) {
  102894. engine.setAlphaMode(this.alphaBlendingMode);
  102895. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102896. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  102897. }
  102898. else {
  102899. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102900. }
  102901. this.onAfterRenderObservable.notifyObservers(this);
  102902. };
  102903. Layer.prototype.dispose = function () {
  102904. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102905. if (vertexBuffer) {
  102906. vertexBuffer.dispose();
  102907. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102908. }
  102909. if (this._indexBuffer) {
  102910. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102911. this._indexBuffer = null;
  102912. }
  102913. if (this.texture) {
  102914. this.texture.dispose();
  102915. this.texture = null;
  102916. }
  102917. // Remove from scene
  102918. var index = this._scene.layers.indexOf(this);
  102919. this._scene.layers.splice(index, 1);
  102920. // Callback
  102921. this.onDisposeObservable.notifyObservers(this);
  102922. this.onDisposeObservable.clear();
  102923. this.onAfterRenderObservable.clear();
  102924. this.onBeforeRenderObservable.clear();
  102925. };
  102926. return Layer;
  102927. }());
  102928. BABYLON.Layer = Layer;
  102929. })(BABYLON || (BABYLON = {}));
  102930. //# sourceMappingURL=babylon.layer.js.map
  102931. var BABYLON;
  102932. (function (BABYLON) {
  102933. var TextureTools = /** @class */ (function () {
  102934. function TextureTools() {
  102935. }
  102936. /**
  102937. * Uses the GPU to create a copy texture rescaled at a given size
  102938. * @param texture Texture to copy from
  102939. * @param width Desired width
  102940. * @param height Desired height
  102941. * @return Generated texture
  102942. */
  102943. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  102944. if (useBilinearMode === void 0) { useBilinearMode = true; }
  102945. var scene = texture.getScene();
  102946. var engine = scene.getEngine();
  102947. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  102948. rtt.wrapU = texture.wrapU;
  102949. rtt.wrapV = texture.wrapV;
  102950. rtt.uOffset = texture.uOffset;
  102951. rtt.vOffset = texture.vOffset;
  102952. rtt.uScale = texture.uScale;
  102953. rtt.vScale = texture.vScale;
  102954. rtt.uAng = texture.uAng;
  102955. rtt.vAng = texture.vAng;
  102956. rtt.wAng = texture.wAng;
  102957. rtt.coordinatesIndex = texture.coordinatesIndex;
  102958. rtt.level = texture.level;
  102959. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  102960. rtt._texture.isReady = false;
  102961. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102962. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102963. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  102964. passPostProcess.getEffect().executeWhenCompiled(function () {
  102965. passPostProcess.onApply = function (effect) {
  102966. effect.setTexture("textureSampler", texture);
  102967. };
  102968. var internalTexture = rtt.getInternalTexture();
  102969. if (internalTexture) {
  102970. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  102971. engine.unBindFramebuffer(internalTexture);
  102972. rtt.disposeFramebufferObjects();
  102973. passPostProcess.dispose();
  102974. internalTexture.isReady = true;
  102975. }
  102976. });
  102977. return rtt;
  102978. };
  102979. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  102980. if (!scene._environmentBRDFTexture) {
  102981. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102982. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102983. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102984. scene._environmentBRDFTexture = texture;
  102985. }
  102986. return scene._environmentBRDFTexture;
  102987. };
  102988. 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=";
  102989. return TextureTools;
  102990. }());
  102991. BABYLON.TextureTools = TextureTools;
  102992. })(BABYLON || (BABYLON = {}));
  102993. //# sourceMappingURL=babylon.textureTools.js.map
  102994. var BABYLON;
  102995. (function (BABYLON) {
  102996. var FramingBehavior = /** @class */ (function () {
  102997. function FramingBehavior() {
  102998. this._mode = FramingBehavior.FitFrustumSidesMode;
  102999. this._radiusScale = 1.0;
  103000. this._positionScale = 0.5;
  103001. this._defaultElevation = 0.3;
  103002. this._elevationReturnTime = 1500;
  103003. this._elevationReturnWaitTime = 1000;
  103004. this._zoomStopsAnimation = false;
  103005. this._framingTime = 1500;
  103006. this._isPointerDown = false;
  103007. this._lastInteractionTime = -Infinity;
  103008. // Framing control
  103009. this._animatables = new Array();
  103010. this._betaIsAnimating = false;
  103011. }
  103012. Object.defineProperty(FramingBehavior.prototype, "name", {
  103013. get: function () {
  103014. return "Framing";
  103015. },
  103016. enumerable: true,
  103017. configurable: true
  103018. });
  103019. Object.defineProperty(FramingBehavior.prototype, "mode", {
  103020. /**
  103021. * Gets current mode used by the behavior.
  103022. */
  103023. get: function () {
  103024. return this._mode;
  103025. },
  103026. /**
  103027. * Sets the current mode used by the behavior
  103028. */
  103029. set: function (mode) {
  103030. this._mode = mode;
  103031. },
  103032. enumerable: true,
  103033. configurable: true
  103034. });
  103035. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  103036. /**
  103037. * Gets the scale applied to the radius
  103038. */
  103039. get: function () {
  103040. return this._radiusScale;
  103041. },
  103042. /**
  103043. * Sets the scale applied to the radius (1 by default)
  103044. */
  103045. set: function (radius) {
  103046. this._radiusScale = radius;
  103047. },
  103048. enumerable: true,
  103049. configurable: true
  103050. });
  103051. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  103052. /**
  103053. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103054. */
  103055. get: function () {
  103056. return this._positionScale;
  103057. },
  103058. /**
  103059. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  103060. */
  103061. set: function (scale) {
  103062. this._positionScale = scale;
  103063. },
  103064. enumerable: true,
  103065. configurable: true
  103066. });
  103067. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  103068. /**
  103069. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103070. * behaviour is triggered, in radians.
  103071. */
  103072. get: function () {
  103073. return this._defaultElevation;
  103074. },
  103075. /**
  103076. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  103077. * behaviour is triggered, in radians.
  103078. */
  103079. set: function (elevation) {
  103080. this._defaultElevation = elevation;
  103081. },
  103082. enumerable: true,
  103083. configurable: true
  103084. });
  103085. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  103086. /**
  103087. * Gets the time (in milliseconds) taken to return to the default beta position.
  103088. * Negative value indicates camera should not return to default.
  103089. */
  103090. get: function () {
  103091. return this._elevationReturnTime;
  103092. },
  103093. /**
  103094. * Sets the time (in milliseconds) taken to return to the default beta position.
  103095. * Negative value indicates camera should not return to default.
  103096. */
  103097. set: function (speed) {
  103098. this._elevationReturnTime = speed;
  103099. },
  103100. enumerable: true,
  103101. configurable: true
  103102. });
  103103. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  103104. /**
  103105. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103106. */
  103107. get: function () {
  103108. return this._elevationReturnWaitTime;
  103109. },
  103110. /**
  103111. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  103112. */
  103113. set: function (time) {
  103114. this._elevationReturnWaitTime = time;
  103115. },
  103116. enumerable: true,
  103117. configurable: true
  103118. });
  103119. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  103120. /**
  103121. * Gets the flag that indicates if user zooming should stop animation.
  103122. */
  103123. get: function () {
  103124. return this._zoomStopsAnimation;
  103125. },
  103126. /**
  103127. * Sets the flag that indicates if user zooming should stop animation.
  103128. */
  103129. set: function (flag) {
  103130. this._zoomStopsAnimation = flag;
  103131. },
  103132. enumerable: true,
  103133. configurable: true
  103134. });
  103135. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  103136. /**
  103137. * Gets the transition time when framing the mesh, in milliseconds
  103138. */
  103139. get: function () {
  103140. return this._framingTime;
  103141. },
  103142. /**
  103143. * Sets the transition time when framing the mesh, in milliseconds
  103144. */
  103145. set: function (time) {
  103146. this._framingTime = time;
  103147. },
  103148. enumerable: true,
  103149. configurable: true
  103150. });
  103151. FramingBehavior.prototype.init = function () {
  103152. // Do notihng
  103153. };
  103154. FramingBehavior.prototype.attach = function (camera) {
  103155. var _this = this;
  103156. this._attachedCamera = camera;
  103157. var scene = this._attachedCamera.getScene();
  103158. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  103159. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103160. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103161. _this._isPointerDown = true;
  103162. return;
  103163. }
  103164. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103165. _this._isPointerDown = false;
  103166. }
  103167. });
  103168. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103169. if (mesh) {
  103170. _this.zoomOnMesh(mesh);
  103171. }
  103172. });
  103173. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103174. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103175. _this._applyUserInteraction();
  103176. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  103177. // back to the default position after a given timeout
  103178. _this._maintainCameraAboveGround();
  103179. });
  103180. };
  103181. FramingBehavior.prototype.detach = function () {
  103182. if (!this._attachedCamera) {
  103183. return;
  103184. }
  103185. var scene = this._attachedCamera.getScene();
  103186. if (this._onPrePointerObservableObserver) {
  103187. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103188. }
  103189. if (this._onAfterCheckInputsObserver) {
  103190. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103191. }
  103192. if (this._onMeshTargetChangedObserver) {
  103193. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103194. }
  103195. this._attachedCamera = null;
  103196. };
  103197. /**
  103198. * Targets the given mesh and updates zoom level accordingly.
  103199. * @param mesh The mesh to target.
  103200. * @param radius Optional. If a cached radius position already exists, overrides default.
  103201. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103202. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103203. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103204. */
  103205. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103206. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103207. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103208. mesh.computeWorldMatrix(true);
  103209. var boundingBox = mesh.getBoundingInfo().boundingBox;
  103210. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  103211. };
  103212. /**
  103213. * Targets the given mesh with its children and updates zoom level accordingly.
  103214. * @param mesh The mesh to target.
  103215. * @param radius Optional. If a cached radius position already exists, overrides default.
  103216. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103217. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103218. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103219. */
  103220. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  103221. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103222. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103223. mesh.computeWorldMatrix(true);
  103224. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  103225. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  103226. };
  103227. /**
  103228. * Targets the given meshes with their children and updates zoom level accordingly.
  103229. * @param meshes The mesh to target.
  103230. * @param radius Optional. If a cached radius position already exists, overrides default.
  103231. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103232. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103233. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103234. */
  103235. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  103236. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103237. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103238. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  103239. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  103240. for (var i = 0; i < meshes.length; i++) {
  103241. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  103242. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  103243. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  103244. }
  103245. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  103246. };
  103247. /**
  103248. * Targets the given mesh and updates zoom level accordingly.
  103249. * @param mesh The mesh to target.
  103250. * @param radius Optional. If a cached radius position already exists, overrides default.
  103251. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  103252. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  103253. * @param onAnimationEnd Callback triggered at the end of the framing animation
  103254. */
  103255. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  103256. var _this = this;
  103257. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  103258. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  103259. var zoomTarget;
  103260. if (!this._attachedCamera) {
  103261. return;
  103262. }
  103263. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  103264. var bottom = minimumWorld.y;
  103265. var top = maximumWorld.y;
  103266. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  103267. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  103268. if (focusOnOriginXZ) {
  103269. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  103270. }
  103271. else {
  103272. var centerWorld = minimumWorld.add(radiusWorld);
  103273. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  103274. }
  103275. if (!this._vectorTransition) {
  103276. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  103277. }
  103278. this._betaIsAnimating = true;
  103279. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  103280. if (animatable) {
  103281. this._animatables.push(animatable);
  103282. }
  103283. // sets the radius and lower radius bounds
  103284. // Small delta ensures camera is not always at lower zoom limit.
  103285. var radius = 0;
  103286. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  103287. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103288. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  103289. radius = position;
  103290. }
  103291. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103292. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  103293. if (this._attachedCamera.lowerRadiusLimit === null) {
  103294. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  103295. }
  103296. }
  103297. // Set sensibilities
  103298. var extend = maximumWorld.subtract(minimumWorld).length();
  103299. this._attachedCamera.panningSensibility = 5000 / extend;
  103300. this._attachedCamera.wheelPrecision = 100 / radius;
  103301. // transition to new radius
  103302. if (!this._radiusTransition) {
  103303. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103304. }
  103305. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  103306. _this.stopAllAnimations();
  103307. if (onAnimationEnd) {
  103308. onAnimationEnd();
  103309. }
  103310. if (_this._attachedCamera) {
  103311. _this._attachedCamera.storeState();
  103312. }
  103313. });
  103314. if (animatable) {
  103315. this._animatables.push(animatable);
  103316. }
  103317. };
  103318. /**
  103319. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  103320. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  103321. * frustum width.
  103322. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  103323. * to fully enclose the mesh in the viewing frustum.
  103324. */
  103325. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  103326. var size = maximumWorld.subtract(minimumWorld);
  103327. var boxVectorGlobalDiagonal = size.length();
  103328. var frustumSlope = this._getFrustumSlope();
  103329. // Formula for setting distance
  103330. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  103331. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  103332. // Horizon distance
  103333. var radius = radiusWithoutFraming * this._radiusScale;
  103334. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  103335. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  103336. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  103337. var camera = this._attachedCamera;
  103338. if (!camera) {
  103339. return 0;
  103340. }
  103341. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  103342. // Don't exceed the requested limit
  103343. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  103344. }
  103345. // Don't exceed the upper radius limit
  103346. if (camera.upperRadiusLimit) {
  103347. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  103348. }
  103349. return distance;
  103350. };
  103351. /**
  103352. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  103353. * is automatically returned to its default position (expected to be above ground plane).
  103354. */
  103355. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  103356. var _this = this;
  103357. if (this._elevationReturnTime < 0) {
  103358. return;
  103359. }
  103360. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  103361. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  103362. var limitBeta = Math.PI * 0.5;
  103363. // Bring the camera back up if below the ground plane
  103364. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  103365. this._betaIsAnimating = true;
  103366. //Transition to new position
  103367. this.stopAllAnimations();
  103368. if (!this._betaTransition) {
  103369. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  103370. }
  103371. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  103372. _this._clearAnimationLocks();
  103373. _this.stopAllAnimations();
  103374. });
  103375. if (animatabe) {
  103376. this._animatables.push(animatabe);
  103377. }
  103378. }
  103379. };
  103380. /**
  103381. * Returns the frustum slope based on the canvas ratio and camera FOV
  103382. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  103383. */
  103384. FramingBehavior.prototype._getFrustumSlope = function () {
  103385. // Calculate the viewport ratio
  103386. // Aspect Ratio is Height/Width.
  103387. var camera = this._attachedCamera;
  103388. if (!camera) {
  103389. return BABYLON.Vector2.Zero();
  103390. }
  103391. var engine = camera.getScene().getEngine();
  103392. var aspectRatio = engine.getAspectRatio(camera);
  103393. // Camera FOV is the vertical field of view (top-bottom) in radians.
  103394. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  103395. var frustumSlopeY = Math.tan(camera.fov / 2);
  103396. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  103397. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  103398. // along the forward vector.
  103399. var frustumSlopeX = frustumSlopeY * aspectRatio;
  103400. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  103401. };
  103402. /**
  103403. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  103404. */
  103405. FramingBehavior.prototype._clearAnimationLocks = function () {
  103406. this._betaIsAnimating = false;
  103407. };
  103408. /**
  103409. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103410. */
  103411. FramingBehavior.prototype._applyUserInteraction = function () {
  103412. if (this.isUserIsMoving) {
  103413. this._lastInteractionTime = BABYLON.Tools.Now;
  103414. this.stopAllAnimations();
  103415. this._clearAnimationLocks();
  103416. }
  103417. };
  103418. /**
  103419. * Stops and removes all animations that have been applied to the camera
  103420. */
  103421. FramingBehavior.prototype.stopAllAnimations = function () {
  103422. if (this._attachedCamera) {
  103423. this._attachedCamera.animations = [];
  103424. }
  103425. while (this._animatables.length) {
  103426. if (this._animatables[0]) {
  103427. this._animatables[0].onAnimationEnd = null;
  103428. this._animatables[0].stop();
  103429. }
  103430. this._animatables.shift();
  103431. }
  103432. };
  103433. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  103434. /**
  103435. * Gets a value indicating if the user is moving the camera
  103436. */
  103437. get: function () {
  103438. if (!this._attachedCamera) {
  103439. return false;
  103440. }
  103441. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103442. this._attachedCamera.inertialBetaOffset !== 0 ||
  103443. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103444. this._attachedCamera.inertialPanningX !== 0 ||
  103445. this._attachedCamera.inertialPanningY !== 0 ||
  103446. this._isPointerDown;
  103447. },
  103448. enumerable: true,
  103449. configurable: true
  103450. });
  103451. /**
  103452. * The easing function used by animations
  103453. */
  103454. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  103455. /**
  103456. * The easing mode used by animations
  103457. */
  103458. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  103459. // Statics
  103460. /**
  103461. * The camera can move all the way towards the mesh.
  103462. */
  103463. FramingBehavior.IgnoreBoundsSizeMode = 0;
  103464. /**
  103465. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  103466. */
  103467. FramingBehavior.FitFrustumSidesMode = 1;
  103468. return FramingBehavior;
  103469. }());
  103470. BABYLON.FramingBehavior = FramingBehavior;
  103471. })(BABYLON || (BABYLON = {}));
  103472. //# sourceMappingURL=babylon.framingBehavior.js.map
  103473. var BABYLON;
  103474. (function (BABYLON) {
  103475. /**
  103476. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  103477. */
  103478. var BouncingBehavior = /** @class */ (function () {
  103479. function BouncingBehavior() {
  103480. /**
  103481. * The duration of the animation, in milliseconds
  103482. */
  103483. this.transitionDuration = 450;
  103484. /**
  103485. * Length of the distance animated by the transition when lower radius is reached
  103486. */
  103487. this.lowerRadiusTransitionRange = 2;
  103488. /**
  103489. * Length of the distance animated by the transition when upper radius is reached
  103490. */
  103491. this.upperRadiusTransitionRange = -2;
  103492. this._autoTransitionRange = false;
  103493. // Animations
  103494. this._radiusIsAnimating = false;
  103495. this._radiusBounceTransition = null;
  103496. this._animatables = new Array();
  103497. }
  103498. Object.defineProperty(BouncingBehavior.prototype, "name", {
  103499. get: function () {
  103500. return "Bouncing";
  103501. },
  103502. enumerable: true,
  103503. configurable: true
  103504. });
  103505. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  103506. /**
  103507. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103508. */
  103509. get: function () {
  103510. return this._autoTransitionRange;
  103511. },
  103512. /**
  103513. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  103514. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  103515. */
  103516. set: function (value) {
  103517. var _this = this;
  103518. if (this._autoTransitionRange === value) {
  103519. return;
  103520. }
  103521. this._autoTransitionRange = value;
  103522. var camera = this._attachedCamera;
  103523. if (!camera) {
  103524. return;
  103525. }
  103526. if (value) {
  103527. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  103528. if (!mesh) {
  103529. return;
  103530. }
  103531. mesh.computeWorldMatrix(true);
  103532. var diagonal = mesh.getBoundingInfo().diagonalLength;
  103533. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  103534. _this.upperRadiusTransitionRange = diagonal * 0.05;
  103535. });
  103536. }
  103537. else if (this._onMeshTargetChangedObserver) {
  103538. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103539. }
  103540. },
  103541. enumerable: true,
  103542. configurable: true
  103543. });
  103544. BouncingBehavior.prototype.init = function () {
  103545. // Do notihng
  103546. };
  103547. BouncingBehavior.prototype.attach = function (camera) {
  103548. var _this = this;
  103549. this._attachedCamera = camera;
  103550. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103551. if (!_this._attachedCamera) {
  103552. return;
  103553. }
  103554. // Add the bounce animation to the lower radius limit
  103555. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  103556. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  103557. }
  103558. // Add the bounce animation to the upper radius limit
  103559. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  103560. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  103561. }
  103562. });
  103563. };
  103564. BouncingBehavior.prototype.detach = function () {
  103565. if (!this._attachedCamera) {
  103566. return;
  103567. }
  103568. if (this._onAfterCheckInputsObserver) {
  103569. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103570. }
  103571. if (this._onMeshTargetChangedObserver) {
  103572. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  103573. }
  103574. this._attachedCamera = null;
  103575. };
  103576. /**
  103577. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  103578. * @param radiusLimit The limit to check against.
  103579. * @return Bool to indicate if at limit.
  103580. */
  103581. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  103582. if (!this._attachedCamera) {
  103583. return false;
  103584. }
  103585. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  103586. return true;
  103587. }
  103588. return false;
  103589. };
  103590. /**
  103591. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  103592. * @param radiusDelta The delta by which to animate to. Can be negative.
  103593. */
  103594. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  103595. var _this = this;
  103596. if (!this._attachedCamera) {
  103597. return;
  103598. }
  103599. if (!this._radiusBounceTransition) {
  103600. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  103601. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  103602. }
  103603. // Prevent zoom until bounce has completed
  103604. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  103605. this._attachedCamera.wheelPrecision = Infinity;
  103606. this._attachedCamera.inertialRadiusOffset = 0;
  103607. // Animate to the radius limit
  103608. this.stopAllAnimations();
  103609. this._radiusIsAnimating = true;
  103610. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  103611. if (animatable) {
  103612. this._animatables.push(animatable);
  103613. }
  103614. };
  103615. /**
  103616. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  103617. */
  103618. BouncingBehavior.prototype._clearAnimationLocks = function () {
  103619. this._radiusIsAnimating = false;
  103620. if (this._attachedCamera) {
  103621. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  103622. }
  103623. };
  103624. /**
  103625. * Stops and removes all animations that have been applied to the camera
  103626. */
  103627. BouncingBehavior.prototype.stopAllAnimations = function () {
  103628. if (this._attachedCamera) {
  103629. this._attachedCamera.animations = [];
  103630. }
  103631. while (this._animatables.length) {
  103632. this._animatables[0].onAnimationEnd = null;
  103633. this._animatables[0].stop();
  103634. this._animatables.shift();
  103635. }
  103636. };
  103637. /**
  103638. * The easing function used by animations
  103639. */
  103640. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  103641. /**
  103642. * The easing mode used by animations
  103643. */
  103644. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  103645. return BouncingBehavior;
  103646. }());
  103647. BABYLON.BouncingBehavior = BouncingBehavior;
  103648. })(BABYLON || (BABYLON = {}));
  103649. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  103650. var BABYLON;
  103651. (function (BABYLON) {
  103652. var AutoRotationBehavior = /** @class */ (function () {
  103653. function AutoRotationBehavior() {
  103654. this._zoomStopsAnimation = false;
  103655. this._idleRotationSpeed = 0.05;
  103656. this._idleRotationWaitTime = 2000;
  103657. this._idleRotationSpinupTime = 2000;
  103658. this._isPointerDown = false;
  103659. this._lastFrameTime = null;
  103660. this._lastInteractionTime = -Infinity;
  103661. this._cameraRotationSpeed = 0;
  103662. this._lastFrameRadius = 0;
  103663. }
  103664. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  103665. get: function () {
  103666. return "AutoRotation";
  103667. },
  103668. enumerable: true,
  103669. configurable: true
  103670. });
  103671. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  103672. /**
  103673. * Gets the flag that indicates if user zooming should stop animation.
  103674. */
  103675. get: function () {
  103676. return this._zoomStopsAnimation;
  103677. },
  103678. /**
  103679. * Sets the flag that indicates if user zooming should stop animation.
  103680. */
  103681. set: function (flag) {
  103682. this._zoomStopsAnimation = flag;
  103683. },
  103684. enumerable: true,
  103685. configurable: true
  103686. });
  103687. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  103688. /**
  103689. * Gets the default speed at which the camera rotates around the model.
  103690. */
  103691. get: function () {
  103692. return this._idleRotationSpeed;
  103693. },
  103694. /**
  103695. * Sets the default speed at which the camera rotates around the model.
  103696. */
  103697. set: function (speed) {
  103698. this._idleRotationSpeed = speed;
  103699. },
  103700. enumerable: true,
  103701. configurable: true
  103702. });
  103703. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  103704. /**
  103705. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  103706. */
  103707. get: function () {
  103708. return this._idleRotationWaitTime;
  103709. },
  103710. /**
  103711. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  103712. */
  103713. set: function (time) {
  103714. this._idleRotationWaitTime = time;
  103715. },
  103716. enumerable: true,
  103717. configurable: true
  103718. });
  103719. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  103720. /**
  103721. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103722. */
  103723. get: function () {
  103724. return this._idleRotationSpinupTime;
  103725. },
  103726. /**
  103727. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  103728. */
  103729. set: function (time) {
  103730. this._idleRotationSpinupTime = time;
  103731. },
  103732. enumerable: true,
  103733. configurable: true
  103734. });
  103735. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  103736. /**
  103737. * Gets a value indicating if the camera is currently rotating because of this behavior
  103738. */
  103739. get: function () {
  103740. return Math.abs(this._cameraRotationSpeed) > 0;
  103741. },
  103742. enumerable: true,
  103743. configurable: true
  103744. });
  103745. AutoRotationBehavior.prototype.init = function () {
  103746. // Do notihng
  103747. };
  103748. AutoRotationBehavior.prototype.attach = function (camera) {
  103749. var _this = this;
  103750. this._attachedCamera = camera;
  103751. var scene = this._attachedCamera.getScene();
  103752. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  103753. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  103754. _this._isPointerDown = true;
  103755. return;
  103756. }
  103757. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  103758. _this._isPointerDown = false;
  103759. }
  103760. });
  103761. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  103762. var now = BABYLON.Tools.Now;
  103763. var dt = 0;
  103764. if (_this._lastFrameTime != null) {
  103765. dt = now - _this._lastFrameTime;
  103766. }
  103767. _this._lastFrameTime = now;
  103768. // Stop the animation if there is user interaction and the animation should stop for this interaction
  103769. _this._applyUserInteraction();
  103770. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  103771. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  103772. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  103773. // Step camera rotation by rotation speed
  103774. if (_this._attachedCamera) {
  103775. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  103776. }
  103777. });
  103778. };
  103779. AutoRotationBehavior.prototype.detach = function () {
  103780. if (!this._attachedCamera) {
  103781. return;
  103782. }
  103783. var scene = this._attachedCamera.getScene();
  103784. if (this._onPrePointerObservableObserver) {
  103785. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  103786. }
  103787. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  103788. this._attachedCamera = null;
  103789. };
  103790. /**
  103791. * Returns true if user is scrolling.
  103792. * @return true if user is scrolling.
  103793. */
  103794. AutoRotationBehavior.prototype._userIsZooming = function () {
  103795. if (!this._attachedCamera) {
  103796. return false;
  103797. }
  103798. return this._attachedCamera.inertialRadiusOffset !== 0;
  103799. };
  103800. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  103801. if (!this._attachedCamera) {
  103802. return false;
  103803. }
  103804. var zoomHasHitLimit = false;
  103805. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  103806. zoomHasHitLimit = true;
  103807. }
  103808. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  103809. this._lastFrameRadius = this._attachedCamera.radius;
  103810. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  103811. };
  103812. /**
  103813. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  103814. */
  103815. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  103816. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  103817. this._lastInteractionTime = BABYLON.Tools.Now;
  103818. }
  103819. };
  103820. // Tools
  103821. AutoRotationBehavior.prototype._userIsMoving = function () {
  103822. if (!this._attachedCamera) {
  103823. return false;
  103824. }
  103825. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  103826. this._attachedCamera.inertialBetaOffset !== 0 ||
  103827. this._attachedCamera.inertialRadiusOffset !== 0 ||
  103828. this._attachedCamera.inertialPanningX !== 0 ||
  103829. this._attachedCamera.inertialPanningY !== 0 ||
  103830. this._isPointerDown;
  103831. };
  103832. return AutoRotationBehavior;
  103833. }());
  103834. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  103835. })(BABYLON || (BABYLON = {}));
  103836. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  103837. var BABYLON;
  103838. (function (BABYLON) {
  103839. var NullEngineOptions = /** @class */ (function () {
  103840. function NullEngineOptions() {
  103841. this.renderWidth = 512;
  103842. this.renderHeight = 256;
  103843. this.textureSize = 512;
  103844. this.deterministicLockstep = false;
  103845. this.lockstepMaxSteps = 4;
  103846. }
  103847. return NullEngineOptions;
  103848. }());
  103849. BABYLON.NullEngineOptions = NullEngineOptions;
  103850. /**
  103851. * The null engine class provides support for headless version of babylon.js.
  103852. * This can be used in server side scenario or for testing purposes
  103853. */
  103854. var NullEngine = /** @class */ (function (_super) {
  103855. __extends(NullEngine, _super);
  103856. function NullEngine(options) {
  103857. if (options === void 0) { options = new NullEngineOptions(); }
  103858. var _this = _super.call(this, null) || this;
  103859. if (options.deterministicLockstep === undefined) {
  103860. options.deterministicLockstep = false;
  103861. }
  103862. if (options.lockstepMaxSteps === undefined) {
  103863. options.lockstepMaxSteps = 4;
  103864. }
  103865. _this._options = options;
  103866. // Init caps
  103867. // We consider we are on a webgl1 capable device
  103868. _this._caps = new BABYLON.EngineCapabilities();
  103869. _this._caps.maxTexturesImageUnits = 16;
  103870. _this._caps.maxVertexTextureImageUnits = 16;
  103871. _this._caps.maxTextureSize = 512;
  103872. _this._caps.maxCubemapTextureSize = 512;
  103873. _this._caps.maxRenderTextureSize = 512;
  103874. _this._caps.maxVertexAttribs = 16;
  103875. _this._caps.maxVaryingVectors = 16;
  103876. _this._caps.maxFragmentUniformVectors = 16;
  103877. _this._caps.maxVertexUniformVectors = 16;
  103878. // Extensions
  103879. _this._caps.standardDerivatives = false;
  103880. _this._caps.astc = null;
  103881. _this._caps.s3tc = null;
  103882. _this._caps.pvrtc = null;
  103883. _this._caps.etc1 = null;
  103884. _this._caps.etc2 = null;
  103885. _this._caps.textureAnisotropicFilterExtension = null;
  103886. _this._caps.maxAnisotropy = 0;
  103887. _this._caps.uintIndices = false;
  103888. _this._caps.fragmentDepthSupported = false;
  103889. _this._caps.highPrecisionShaderSupported = true;
  103890. _this._caps.colorBufferFloat = false;
  103891. _this._caps.textureFloat = false;
  103892. _this._caps.textureFloatLinearFiltering = false;
  103893. _this._caps.textureFloatRender = false;
  103894. _this._caps.textureHalfFloat = false;
  103895. _this._caps.textureHalfFloatLinearFiltering = false;
  103896. _this._caps.textureHalfFloatRender = false;
  103897. _this._caps.textureLOD = false;
  103898. _this._caps.drawBuffersExtension = false;
  103899. _this._caps.depthTextureExtension = false;
  103900. _this._caps.vertexArrayObject = false;
  103901. _this._caps.instancedArrays = false;
  103902. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  103903. // Wrappers
  103904. if (typeof URL === "undefined") {
  103905. URL = {
  103906. createObjectURL: function () { },
  103907. revokeObjectURL: function () { }
  103908. };
  103909. }
  103910. if (typeof Blob === "undefined") {
  103911. Blob = function () { };
  103912. }
  103913. return _this;
  103914. }
  103915. NullEngine.prototype.isDeterministicLockStep = function () {
  103916. return this._options.deterministicLockstep;
  103917. };
  103918. NullEngine.prototype.getLockstepMaxSteps = function () {
  103919. return this._options.lockstepMaxSteps;
  103920. };
  103921. NullEngine.prototype.getHardwareScalingLevel = function () {
  103922. return 1.0;
  103923. };
  103924. NullEngine.prototype.createVertexBuffer = function (vertices) {
  103925. return {
  103926. capacity: 0,
  103927. references: 1,
  103928. is32Bits: false
  103929. };
  103930. };
  103931. NullEngine.prototype.createIndexBuffer = function (indices) {
  103932. return {
  103933. capacity: 0,
  103934. references: 1,
  103935. is32Bits: false
  103936. };
  103937. };
  103938. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  103939. if (stencil === void 0) { stencil = false; }
  103940. };
  103941. NullEngine.prototype.getRenderWidth = function (useScreen) {
  103942. if (useScreen === void 0) { useScreen = false; }
  103943. if (!useScreen && this._currentRenderTarget) {
  103944. return this._currentRenderTarget.width;
  103945. }
  103946. return this._options.renderWidth;
  103947. };
  103948. NullEngine.prototype.getRenderHeight = function (useScreen) {
  103949. if (useScreen === void 0) { useScreen = false; }
  103950. if (!useScreen && this._currentRenderTarget) {
  103951. return this._currentRenderTarget.height;
  103952. }
  103953. return this._options.renderHeight;
  103954. };
  103955. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  103956. this._cachedViewport = viewport;
  103957. };
  103958. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  103959. return {
  103960. transformFeedback: null,
  103961. __SPECTOR_rebuildProgram: null
  103962. };
  103963. };
  103964. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  103965. return [];
  103966. };
  103967. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  103968. return [];
  103969. };
  103970. NullEngine.prototype.bindSamplers = function (effect) {
  103971. this._currentEffect = null;
  103972. };
  103973. NullEngine.prototype.enableEffect = function (effect) {
  103974. this._currentEffect = effect;
  103975. if (effect.onBind) {
  103976. effect.onBind(effect);
  103977. }
  103978. if (effect._onBindObservable) {
  103979. effect._onBindObservable.notifyObservers(effect);
  103980. }
  103981. };
  103982. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  103983. if (zOffset === void 0) { zOffset = 0; }
  103984. if (reverseSide === void 0) { reverseSide = false; }
  103985. };
  103986. NullEngine.prototype.setIntArray = function (uniform, array) {
  103987. };
  103988. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  103989. };
  103990. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  103991. };
  103992. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  103993. };
  103994. NullEngine.prototype.setFloatArray = function (uniform, array) {
  103995. };
  103996. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  103997. };
  103998. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  103999. };
  104000. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  104001. };
  104002. NullEngine.prototype.setArray = function (uniform, array) {
  104003. };
  104004. NullEngine.prototype.setArray2 = function (uniform, array) {
  104005. };
  104006. NullEngine.prototype.setArray3 = function (uniform, array) {
  104007. };
  104008. NullEngine.prototype.setArray4 = function (uniform, array) {
  104009. };
  104010. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  104011. };
  104012. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  104013. };
  104014. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  104015. };
  104016. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  104017. };
  104018. NullEngine.prototype.setFloat = function (uniform, value) {
  104019. };
  104020. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  104021. };
  104022. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  104023. };
  104024. NullEngine.prototype.setBool = function (uniform, bool) {
  104025. };
  104026. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  104027. };
  104028. NullEngine.prototype.setColor3 = function (uniform, color3) {
  104029. };
  104030. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  104031. };
  104032. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  104033. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  104034. if (this._alphaMode === mode) {
  104035. return;
  104036. }
  104037. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  104038. if (!noDepthWriteChange) {
  104039. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  104040. }
  104041. this._alphaMode = mode;
  104042. };
  104043. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  104044. };
  104045. NullEngine.prototype.wipeCaches = function (bruteForce) {
  104046. if (this.preventCacheWipeBetweenFrames) {
  104047. return;
  104048. }
  104049. this.resetTextureCache();
  104050. this._currentEffect = null;
  104051. if (bruteForce) {
  104052. this._currentProgram = null;
  104053. this._stencilState.reset();
  104054. this._depthCullingState.reset();
  104055. this._alphaState.reset();
  104056. }
  104057. this._cachedVertexBuffers = null;
  104058. this._cachedIndexBuffer = null;
  104059. this._cachedEffectForVertexBuffers = null;
  104060. };
  104061. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  104062. };
  104063. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  104064. };
  104065. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  104066. };
  104067. /** @hidden */
  104068. NullEngine.prototype._createTexture = function () {
  104069. return {};
  104070. };
  104071. /** @hidden */
  104072. NullEngine.prototype._releaseTexture = function (texture) {
  104073. };
  104074. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  104075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  104076. if (onLoad === void 0) { onLoad = null; }
  104077. if (onError === void 0) { onError = null; }
  104078. if (buffer === void 0) { buffer = null; }
  104079. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  104080. var url = String(urlArg);
  104081. texture.url = url;
  104082. texture.generateMipMaps = !noMipmap;
  104083. texture.samplingMode = samplingMode;
  104084. texture.invertY = invertY;
  104085. texture.baseWidth = this._options.textureSize;
  104086. texture.baseHeight = this._options.textureSize;
  104087. texture.width = this._options.textureSize;
  104088. texture.height = this._options.textureSize;
  104089. if (format) {
  104090. texture.format = format;
  104091. }
  104092. texture.isReady = true;
  104093. if (onLoad) {
  104094. onLoad();
  104095. }
  104096. this._internalTexturesCache.push(texture);
  104097. return texture;
  104098. };
  104099. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  104100. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  104101. if (options !== undefined && typeof options === "object") {
  104102. fullOptions.generateMipMaps = options.generateMipMaps;
  104103. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  104104. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  104105. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  104106. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  104107. }
  104108. else {
  104109. fullOptions.generateMipMaps = options;
  104110. fullOptions.generateDepthBuffer = true;
  104111. fullOptions.generateStencilBuffer = false;
  104112. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104113. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  104114. }
  104115. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  104116. var width = size.width || size;
  104117. var height = size.height || size;
  104118. texture._depthStencilBuffer = {};
  104119. texture._framebuffer = {};
  104120. texture.baseWidth = width;
  104121. texture.baseHeight = height;
  104122. texture.width = width;
  104123. texture.height = height;
  104124. texture.isReady = true;
  104125. texture.samples = 1;
  104126. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  104127. texture.samplingMode = fullOptions.samplingMode;
  104128. texture.type = fullOptions.type;
  104129. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  104130. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  104131. this._internalTexturesCache.push(texture);
  104132. return texture;
  104133. };
  104134. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  104135. texture.samplingMode = samplingMode;
  104136. };
  104137. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  104138. if (this._currentRenderTarget) {
  104139. this.unBindFramebuffer(this._currentRenderTarget);
  104140. }
  104141. this._currentRenderTarget = texture;
  104142. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  104143. if (this._cachedViewport && !forceFullscreenViewport) {
  104144. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  104145. }
  104146. };
  104147. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  104148. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  104149. this._currentRenderTarget = null;
  104150. if (onBeforeUnbind) {
  104151. if (texture._MSAAFramebuffer) {
  104152. this._currentFramebuffer = texture._framebuffer;
  104153. }
  104154. onBeforeUnbind();
  104155. }
  104156. this._currentFramebuffer = null;
  104157. };
  104158. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  104159. var vbo = {
  104160. capacity: 1,
  104161. references: 1,
  104162. is32Bits: false
  104163. };
  104164. return vbo;
  104165. };
  104166. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  104167. if (premulAlpha === void 0) { premulAlpha = false; }
  104168. };
  104169. /**
  104170. * @hidden
  104171. * Get the current error code of the webGL context
  104172. * @returns the error code
  104173. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  104174. */
  104175. NullEngine.prototype.getError = function () {
  104176. return 0;
  104177. };
  104178. /** @hidden */
  104179. NullEngine.prototype._getUnpackAlignement = function () {
  104180. return 1;
  104181. };
  104182. /** @hidden */
  104183. NullEngine.prototype._unpackFlipY = function (value) {
  104184. };
  104185. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  104186. if (offset === void 0) { offset = 0; }
  104187. };
  104188. /**
  104189. * Updates a dynamic vertex buffer.
  104190. * @param vertexBuffer the vertex buffer to update
  104191. * @param data the data used to update the vertex buffer
  104192. * @param byteOffset the byte offset of the data (optional)
  104193. * @param byteLength the byte length of the data (optional)
  104194. */
  104195. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  104196. };
  104197. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  104198. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  104199. this._boundTexturesCache[this._activeChannel] = texture;
  104200. return true;
  104201. }
  104202. return false;
  104203. };
  104204. /** @hidden */
  104205. NullEngine.prototype._bindTexture = function (channel, texture) {
  104206. if (channel < 0) {
  104207. return;
  104208. }
  104209. this._bindTextureDirectly(0, texture);
  104210. };
  104211. /** @hidden */
  104212. NullEngine.prototype._releaseBuffer = function (buffer) {
  104213. buffer.references--;
  104214. if (buffer.references === 0) {
  104215. return true;
  104216. }
  104217. return false;
  104218. };
  104219. NullEngine.prototype.releaseEffects = function () {
  104220. };
  104221. NullEngine.prototype.displayLoadingUI = function () {
  104222. };
  104223. NullEngine.prototype.hideLoadingUI = function () {
  104224. };
  104225. /** @hidden */
  104226. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  104227. if (faceIndex === void 0) { faceIndex = 0; }
  104228. if (lod === void 0) { lod = 0; }
  104229. };
  104230. /** @hidden */
  104231. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  104232. if (faceIndex === void 0) { faceIndex = 0; }
  104233. if (lod === void 0) { lod = 0; }
  104234. };
  104235. /** @hidden */
  104236. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  104237. if (faceIndex === void 0) { faceIndex = 0; }
  104238. if (lod === void 0) { lod = 0; }
  104239. };
  104240. /** @hidden */
  104241. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  104242. if (faceIndex === void 0) { faceIndex = 0; }
  104243. if (lod === void 0) { lod = 0; }
  104244. };
  104245. return NullEngine;
  104246. }(BABYLON.Engine));
  104247. BABYLON.NullEngine = NullEngine;
  104248. })(BABYLON || (BABYLON = {}));
  104249. //# sourceMappingURL=babylon.nullEngine.js.map
  104250. var BABYLON;
  104251. (function (BABYLON) {
  104252. /**
  104253. * This class can be used to get instrumentation data from a Babylon engine
  104254. */
  104255. var EngineInstrumentation = /** @class */ (function () {
  104256. function EngineInstrumentation(engine) {
  104257. this.engine = engine;
  104258. this._captureGPUFrameTime = false;
  104259. this._gpuFrameTime = new BABYLON.PerfCounter();
  104260. this._captureShaderCompilationTime = false;
  104261. this._shaderCompilationTime = new BABYLON.PerfCounter();
  104262. // Observers
  104263. this._onBeginFrameObserver = null;
  104264. this._onEndFrameObserver = null;
  104265. this._onBeforeShaderCompilationObserver = null;
  104266. this._onAfterShaderCompilationObserver = null;
  104267. }
  104268. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  104269. // Properties
  104270. /**
  104271. * Gets the perf counter used for GPU frame time
  104272. */
  104273. get: function () {
  104274. return this._gpuFrameTime;
  104275. },
  104276. enumerable: true,
  104277. configurable: true
  104278. });
  104279. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  104280. /**
  104281. * Gets the GPU frame time capture status
  104282. */
  104283. get: function () {
  104284. return this._captureGPUFrameTime;
  104285. },
  104286. /**
  104287. * Enable or disable the GPU frame time capture
  104288. */
  104289. set: function (value) {
  104290. var _this = this;
  104291. if (value === this._captureGPUFrameTime) {
  104292. return;
  104293. }
  104294. this._captureGPUFrameTime = value;
  104295. if (value) {
  104296. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  104297. if (!_this._gpuFrameTimeToken) {
  104298. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  104299. }
  104300. });
  104301. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  104302. if (!_this._gpuFrameTimeToken) {
  104303. return;
  104304. }
  104305. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  104306. if (time > -1) {
  104307. _this._gpuFrameTimeToken = null;
  104308. _this._gpuFrameTime.fetchNewFrame();
  104309. _this._gpuFrameTime.addCount(time, true);
  104310. }
  104311. });
  104312. }
  104313. else {
  104314. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104315. this._onBeginFrameObserver = null;
  104316. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104317. this._onEndFrameObserver = null;
  104318. }
  104319. },
  104320. enumerable: true,
  104321. configurable: true
  104322. });
  104323. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  104324. /**
  104325. * Gets the perf counter used for shader compilation time
  104326. */
  104327. get: function () {
  104328. return this._shaderCompilationTime;
  104329. },
  104330. enumerable: true,
  104331. configurable: true
  104332. });
  104333. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  104334. /**
  104335. * Gets the shader compilation time capture status
  104336. */
  104337. get: function () {
  104338. return this._captureShaderCompilationTime;
  104339. },
  104340. /**
  104341. * Enable or disable the shader compilation time capture
  104342. */
  104343. set: function (value) {
  104344. var _this = this;
  104345. if (value === this._captureShaderCompilationTime) {
  104346. return;
  104347. }
  104348. this._captureShaderCompilationTime = value;
  104349. if (value) {
  104350. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  104351. _this._shaderCompilationTime.fetchNewFrame();
  104352. _this._shaderCompilationTime.beginMonitoring();
  104353. });
  104354. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  104355. _this._shaderCompilationTime.endMonitoring();
  104356. });
  104357. }
  104358. else {
  104359. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104360. this._onBeforeShaderCompilationObserver = null;
  104361. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104362. this._onAfterShaderCompilationObserver = null;
  104363. }
  104364. },
  104365. enumerable: true,
  104366. configurable: true
  104367. });
  104368. EngineInstrumentation.prototype.dispose = function () {
  104369. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  104370. this._onBeginFrameObserver = null;
  104371. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  104372. this._onEndFrameObserver = null;
  104373. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  104374. this._onBeforeShaderCompilationObserver = null;
  104375. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  104376. this._onAfterShaderCompilationObserver = null;
  104377. this.engine = null;
  104378. };
  104379. return EngineInstrumentation;
  104380. }());
  104381. BABYLON.EngineInstrumentation = EngineInstrumentation;
  104382. })(BABYLON || (BABYLON = {}));
  104383. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  104384. var BABYLON;
  104385. (function (BABYLON) {
  104386. /**
  104387. * This class can be used to get instrumentation data from a Babylon engine
  104388. */
  104389. var SceneInstrumentation = /** @class */ (function () {
  104390. function SceneInstrumentation(scene) {
  104391. var _this = this;
  104392. this.scene = scene;
  104393. this._captureActiveMeshesEvaluationTime = false;
  104394. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  104395. this._captureRenderTargetsRenderTime = false;
  104396. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  104397. this._captureFrameTime = false;
  104398. this._frameTime = new BABYLON.PerfCounter();
  104399. this._captureRenderTime = false;
  104400. this._renderTime = new BABYLON.PerfCounter();
  104401. this._captureInterFrameTime = false;
  104402. this._interFrameTime = new BABYLON.PerfCounter();
  104403. this._captureParticlesRenderTime = false;
  104404. this._particlesRenderTime = new BABYLON.PerfCounter();
  104405. this._captureSpritesRenderTime = false;
  104406. this._spritesRenderTime = new BABYLON.PerfCounter();
  104407. this._capturePhysicsTime = false;
  104408. this._physicsTime = new BABYLON.PerfCounter();
  104409. this._captureAnimationsTime = false;
  104410. this._animationsTime = new BABYLON.PerfCounter();
  104411. this._captureCameraRenderTime = false;
  104412. this._cameraRenderTime = new BABYLON.PerfCounter();
  104413. // Observers
  104414. this._onBeforeActiveMeshesEvaluationObserver = null;
  104415. this._onAfterActiveMeshesEvaluationObserver = null;
  104416. this._onBeforeRenderTargetsRenderObserver = null;
  104417. this._onAfterRenderTargetsRenderObserver = null;
  104418. this._onAfterRenderObserver = null;
  104419. this._onBeforeDrawPhaseObserver = null;
  104420. this._onAfterDrawPhaseObserver = null;
  104421. this._onBeforeAnimationsObserver = null;
  104422. this._onBeforeParticlesRenderingObserver = null;
  104423. this._onAfterParticlesRenderingObserver = null;
  104424. this._onBeforeSpritesRenderingObserver = null;
  104425. this._onAfterSpritesRenderingObserver = null;
  104426. this._onBeforePhysicsObserver = null;
  104427. this._onAfterPhysicsObserver = null;
  104428. this._onAfterAnimationsObserver = null;
  104429. this._onBeforeCameraRenderObserver = null;
  104430. this._onAfterCameraRenderObserver = null;
  104431. // Before render
  104432. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  104433. if (_this._captureActiveMeshesEvaluationTime) {
  104434. _this._activeMeshesEvaluationTime.fetchNewFrame();
  104435. }
  104436. if (_this._captureRenderTargetsRenderTime) {
  104437. _this._renderTargetsRenderTime.fetchNewFrame();
  104438. }
  104439. if (_this._captureFrameTime) {
  104440. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  104441. _this._frameTime.beginMonitoring();
  104442. }
  104443. if (_this._captureInterFrameTime) {
  104444. _this._interFrameTime.endMonitoring();
  104445. }
  104446. if (_this._captureParticlesRenderTime) {
  104447. _this._particlesRenderTime.fetchNewFrame();
  104448. }
  104449. if (_this._captureSpritesRenderTime) {
  104450. _this._spritesRenderTime.fetchNewFrame();
  104451. }
  104452. if (_this._captureAnimationsTime) {
  104453. _this._animationsTime.beginMonitoring();
  104454. }
  104455. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  104456. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  104457. });
  104458. // After render
  104459. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  104460. if (_this._captureFrameTime) {
  104461. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  104462. _this._frameTime.endMonitoring();
  104463. }
  104464. if (_this._captureRenderTime) {
  104465. _this._renderTime.endMonitoring(false);
  104466. }
  104467. if (_this._captureInterFrameTime) {
  104468. _this._interFrameTime.beginMonitoring();
  104469. }
  104470. });
  104471. }
  104472. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  104473. // Properties
  104474. /**
  104475. * Gets the perf counter used for active meshes evaluation time
  104476. */
  104477. get: function () {
  104478. return this._activeMeshesEvaluationTime;
  104479. },
  104480. enumerable: true,
  104481. configurable: true
  104482. });
  104483. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  104484. /**
  104485. * Gets the active meshes evaluation time capture status
  104486. */
  104487. get: function () {
  104488. return this._captureActiveMeshesEvaluationTime;
  104489. },
  104490. /**
  104491. * Enable or disable the active meshes evaluation time capture
  104492. */
  104493. set: function (value) {
  104494. var _this = this;
  104495. if (value === this._captureActiveMeshesEvaluationTime) {
  104496. return;
  104497. }
  104498. this._captureActiveMeshesEvaluationTime = value;
  104499. if (value) {
  104500. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  104501. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  104502. _this._activeMeshesEvaluationTime.beginMonitoring();
  104503. });
  104504. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  104505. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  104506. _this._activeMeshesEvaluationTime.endMonitoring();
  104507. });
  104508. }
  104509. else {
  104510. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104511. this._onBeforeActiveMeshesEvaluationObserver = null;
  104512. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104513. this._onAfterActiveMeshesEvaluationObserver = null;
  104514. }
  104515. },
  104516. enumerable: true,
  104517. configurable: true
  104518. });
  104519. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  104520. /**
  104521. * Gets the perf counter used for render targets render time
  104522. */
  104523. get: function () {
  104524. return this._renderTargetsRenderTime;
  104525. },
  104526. enumerable: true,
  104527. configurable: true
  104528. });
  104529. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  104530. /**
  104531. * Gets the render targets render time capture status
  104532. */
  104533. get: function () {
  104534. return this._captureRenderTargetsRenderTime;
  104535. },
  104536. /**
  104537. * Enable or disable the render targets render time capture
  104538. */
  104539. set: function (value) {
  104540. var _this = this;
  104541. if (value === this._captureRenderTargetsRenderTime) {
  104542. return;
  104543. }
  104544. this._captureRenderTargetsRenderTime = value;
  104545. if (value) {
  104546. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  104547. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  104548. _this._renderTargetsRenderTime.beginMonitoring();
  104549. });
  104550. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  104551. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  104552. _this._renderTargetsRenderTime.endMonitoring(false);
  104553. });
  104554. }
  104555. else {
  104556. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104557. this._onBeforeRenderTargetsRenderObserver = null;
  104558. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104559. this._onAfterRenderTargetsRenderObserver = null;
  104560. }
  104561. },
  104562. enumerable: true,
  104563. configurable: true
  104564. });
  104565. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  104566. /**
  104567. * Gets the perf counter used for particles render time
  104568. */
  104569. get: function () {
  104570. return this._particlesRenderTime;
  104571. },
  104572. enumerable: true,
  104573. configurable: true
  104574. });
  104575. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  104576. /**
  104577. * Gets the particles render time capture status
  104578. */
  104579. get: function () {
  104580. return this._captureParticlesRenderTime;
  104581. },
  104582. /**
  104583. * Enable or disable the particles render time capture
  104584. */
  104585. set: function (value) {
  104586. var _this = this;
  104587. if (value === this._captureParticlesRenderTime) {
  104588. return;
  104589. }
  104590. this._captureParticlesRenderTime = value;
  104591. if (value) {
  104592. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  104593. BABYLON.Tools.StartPerformanceCounter("Particles");
  104594. _this._particlesRenderTime.beginMonitoring();
  104595. });
  104596. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  104597. BABYLON.Tools.EndPerformanceCounter("Particles");
  104598. _this._particlesRenderTime.endMonitoring(false);
  104599. });
  104600. }
  104601. else {
  104602. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104603. this._onBeforeParticlesRenderingObserver = null;
  104604. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104605. this._onAfterParticlesRenderingObserver = null;
  104606. }
  104607. },
  104608. enumerable: true,
  104609. configurable: true
  104610. });
  104611. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  104612. /**
  104613. * Gets the perf counter used for sprites render time
  104614. */
  104615. get: function () {
  104616. return this._spritesRenderTime;
  104617. },
  104618. enumerable: true,
  104619. configurable: true
  104620. });
  104621. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  104622. /**
  104623. * Gets the sprites render time capture status
  104624. */
  104625. get: function () {
  104626. return this._captureSpritesRenderTime;
  104627. },
  104628. /**
  104629. * Enable or disable the sprites render time capture
  104630. */
  104631. set: function (value) {
  104632. var _this = this;
  104633. if (value === this._captureSpritesRenderTime) {
  104634. return;
  104635. }
  104636. this._captureSpritesRenderTime = value;
  104637. if (value) {
  104638. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  104639. BABYLON.Tools.StartPerformanceCounter("Sprites");
  104640. _this._spritesRenderTime.beginMonitoring();
  104641. });
  104642. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  104643. BABYLON.Tools.EndPerformanceCounter("Sprites");
  104644. _this._spritesRenderTime.endMonitoring(false);
  104645. });
  104646. }
  104647. else {
  104648. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104649. this._onBeforeSpritesRenderingObserver = null;
  104650. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104651. this._onAfterSpritesRenderingObserver = null;
  104652. }
  104653. },
  104654. enumerable: true,
  104655. configurable: true
  104656. });
  104657. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  104658. /**
  104659. * Gets the perf counter used for physics time
  104660. */
  104661. get: function () {
  104662. return this._physicsTime;
  104663. },
  104664. enumerable: true,
  104665. configurable: true
  104666. });
  104667. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  104668. /**
  104669. * Gets the physics time capture status
  104670. */
  104671. get: function () {
  104672. return this._capturePhysicsTime;
  104673. },
  104674. /**
  104675. * Enable or disable the physics time capture
  104676. */
  104677. set: function (value) {
  104678. var _this = this;
  104679. if (value === this._capturePhysicsTime) {
  104680. return;
  104681. }
  104682. this._capturePhysicsTime = value;
  104683. if (value) {
  104684. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  104685. BABYLON.Tools.StartPerformanceCounter("Physics");
  104686. _this._physicsTime.beginMonitoring();
  104687. });
  104688. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  104689. BABYLON.Tools.EndPerformanceCounter("Physics");
  104690. _this._physicsTime.endMonitoring();
  104691. });
  104692. }
  104693. else {
  104694. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104695. this._onBeforePhysicsObserver = null;
  104696. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104697. this._onAfterPhysicsObserver = null;
  104698. }
  104699. },
  104700. enumerable: true,
  104701. configurable: true
  104702. });
  104703. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  104704. /**
  104705. * Gets the perf counter used for animations time
  104706. */
  104707. get: function () {
  104708. return this._animationsTime;
  104709. },
  104710. enumerable: true,
  104711. configurable: true
  104712. });
  104713. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  104714. /**
  104715. * Gets the animations time capture status
  104716. */
  104717. get: function () {
  104718. return this._captureAnimationsTime;
  104719. },
  104720. /**
  104721. * Enable or disable the animations time capture
  104722. */
  104723. set: function (value) {
  104724. var _this = this;
  104725. if (value === this._captureAnimationsTime) {
  104726. return;
  104727. }
  104728. this._captureAnimationsTime = value;
  104729. if (value) {
  104730. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  104731. _this._animationsTime.endMonitoring();
  104732. });
  104733. }
  104734. else {
  104735. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104736. this._onAfterAnimationsObserver = null;
  104737. }
  104738. },
  104739. enumerable: true,
  104740. configurable: true
  104741. });
  104742. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  104743. /**
  104744. * Gets the perf counter used for frame time capture
  104745. */
  104746. get: function () {
  104747. return this._frameTime;
  104748. },
  104749. enumerable: true,
  104750. configurable: true
  104751. });
  104752. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  104753. /**
  104754. * Gets the frame time capture status
  104755. */
  104756. get: function () {
  104757. return this._captureFrameTime;
  104758. },
  104759. /**
  104760. * Enable or disable the frame time capture
  104761. */
  104762. set: function (value) {
  104763. this._captureFrameTime = value;
  104764. },
  104765. enumerable: true,
  104766. configurable: true
  104767. });
  104768. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  104769. /**
  104770. * Gets the perf counter used for inter-frames time capture
  104771. */
  104772. get: function () {
  104773. return this._interFrameTime;
  104774. },
  104775. enumerable: true,
  104776. configurable: true
  104777. });
  104778. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  104779. /**
  104780. * Gets the inter-frames time capture status
  104781. */
  104782. get: function () {
  104783. return this._captureInterFrameTime;
  104784. },
  104785. /**
  104786. * Enable or disable the inter-frames time capture
  104787. */
  104788. set: function (value) {
  104789. this._captureInterFrameTime = value;
  104790. },
  104791. enumerable: true,
  104792. configurable: true
  104793. });
  104794. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  104795. /**
  104796. * Gets the perf counter used for render time capture
  104797. */
  104798. get: function () {
  104799. return this._renderTime;
  104800. },
  104801. enumerable: true,
  104802. configurable: true
  104803. });
  104804. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  104805. /**
  104806. * Gets the render time capture status
  104807. */
  104808. get: function () {
  104809. return this._captureRenderTime;
  104810. },
  104811. /**
  104812. * Enable or disable the render time capture
  104813. */
  104814. set: function (value) {
  104815. var _this = this;
  104816. if (value === this._captureRenderTime) {
  104817. return;
  104818. }
  104819. this._captureRenderTime = value;
  104820. if (value) {
  104821. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  104822. _this._renderTime.beginMonitoring();
  104823. BABYLON.Tools.StartPerformanceCounter("Main render");
  104824. });
  104825. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  104826. _this._renderTime.endMonitoring(false);
  104827. BABYLON.Tools.EndPerformanceCounter("Main render");
  104828. });
  104829. }
  104830. else {
  104831. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104832. this._onBeforeDrawPhaseObserver = null;
  104833. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104834. this._onAfterDrawPhaseObserver = null;
  104835. }
  104836. },
  104837. enumerable: true,
  104838. configurable: true
  104839. });
  104840. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  104841. /**
  104842. * Gets the perf counter used for camera render time capture
  104843. */
  104844. get: function () {
  104845. return this._cameraRenderTime;
  104846. },
  104847. enumerable: true,
  104848. configurable: true
  104849. });
  104850. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  104851. /**
  104852. * Gets the camera render time capture status
  104853. */
  104854. get: function () {
  104855. return this._captureCameraRenderTime;
  104856. },
  104857. /**
  104858. * Enable or disable the camera render time capture
  104859. */
  104860. set: function (value) {
  104861. var _this = this;
  104862. if (value === this._captureCameraRenderTime) {
  104863. return;
  104864. }
  104865. this._captureCameraRenderTime = value;
  104866. if (value) {
  104867. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  104868. _this._cameraRenderTime.beginMonitoring();
  104869. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  104870. });
  104871. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  104872. _this._cameraRenderTime.endMonitoring(false);
  104873. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  104874. });
  104875. }
  104876. else {
  104877. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104878. this._onBeforeCameraRenderObserver = null;
  104879. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104880. this._onAfterCameraRenderObserver = null;
  104881. }
  104882. },
  104883. enumerable: true,
  104884. configurable: true
  104885. });
  104886. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  104887. /**
  104888. * Gets the perf counter used for draw calls
  104889. */
  104890. get: function () {
  104891. return this.scene.getEngine()._drawCalls;
  104892. },
  104893. enumerable: true,
  104894. configurable: true
  104895. });
  104896. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  104897. /**
  104898. * Gets the perf counter used for texture collisions
  104899. */
  104900. get: function () {
  104901. return this.scene.getEngine()._textureCollisions;
  104902. },
  104903. enumerable: true,
  104904. configurable: true
  104905. });
  104906. SceneInstrumentation.prototype.dispose = function () {
  104907. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104908. this._onAfterRenderObserver = null;
  104909. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  104910. this._onBeforeActiveMeshesEvaluationObserver = null;
  104911. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  104912. this._onAfterActiveMeshesEvaluationObserver = null;
  104913. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  104914. this._onBeforeRenderTargetsRenderObserver = null;
  104915. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  104916. this._onAfterRenderTargetsRenderObserver = null;
  104917. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  104918. this._onBeforeAnimationsObserver = null;
  104919. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  104920. this._onBeforeParticlesRenderingObserver = null;
  104921. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  104922. this._onAfterParticlesRenderingObserver = null;
  104923. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  104924. this._onBeforeSpritesRenderingObserver = null;
  104925. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  104926. this._onAfterSpritesRenderingObserver = null;
  104927. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  104928. this._onBeforeDrawPhaseObserver = null;
  104929. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  104930. this._onAfterDrawPhaseObserver = null;
  104931. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  104932. this._onBeforePhysicsObserver = null;
  104933. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  104934. this._onAfterPhysicsObserver = null;
  104935. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  104936. this._onAfterAnimationsObserver = null;
  104937. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  104938. this._onBeforeCameraRenderObserver = null;
  104939. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  104940. this._onAfterCameraRenderObserver = null;
  104941. this.scene = null;
  104942. };
  104943. return SceneInstrumentation;
  104944. }());
  104945. BABYLON.SceneInstrumentation = SceneInstrumentation;
  104946. })(BABYLON || (BABYLON = {}));
  104947. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  104948. var BABYLON;
  104949. (function (BABYLON) {
  104950. /**
  104951. * @hidden
  104952. **/
  104953. var _TimeToken = /** @class */ (function () {
  104954. function _TimeToken() {
  104955. this._timeElapsedQueryEnded = false;
  104956. }
  104957. return _TimeToken;
  104958. }());
  104959. BABYLON._TimeToken = _TimeToken;
  104960. })(BABYLON || (BABYLON = {}));
  104961. //# sourceMappingURL=babylon.timeToken.js.map
  104962. var BABYLON;
  104963. (function (BABYLON) {
  104964. /**
  104965. * Background material defines definition.
  104966. * @hidden Mainly internal Use
  104967. */
  104968. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  104969. __extends(BackgroundMaterialDefines, _super);
  104970. /**
  104971. * Constructor of the defines.
  104972. */
  104973. function BackgroundMaterialDefines() {
  104974. var _this = _super.call(this) || this;
  104975. /**
  104976. * True if the diffuse texture is in use.
  104977. */
  104978. _this.DIFFUSE = false;
  104979. /**
  104980. * The direct UV channel to use.
  104981. */
  104982. _this.DIFFUSEDIRECTUV = 0;
  104983. /**
  104984. * True if the diffuse texture is in gamma space.
  104985. */
  104986. _this.GAMMADIFFUSE = false;
  104987. /**
  104988. * True if the diffuse texture has opacity in the alpha channel.
  104989. */
  104990. _this.DIFFUSEHASALPHA = false;
  104991. /**
  104992. * True if you want the material to fade to transparent at grazing angle.
  104993. */
  104994. _this.OPACITYFRESNEL = false;
  104995. /**
  104996. * True if an extra blur needs to be added in the reflection.
  104997. */
  104998. _this.REFLECTIONBLUR = false;
  104999. /**
  105000. * True if you want the material to fade to reflection at grazing angle.
  105001. */
  105002. _this.REFLECTIONFRESNEL = false;
  105003. /**
  105004. * True if you want the material to falloff as far as you move away from the scene center.
  105005. */
  105006. _this.REFLECTIONFALLOFF = false;
  105007. /**
  105008. * False if the current Webgl implementation does not support the texture lod extension.
  105009. */
  105010. _this.TEXTURELODSUPPORT = false;
  105011. /**
  105012. * True to ensure the data are premultiplied.
  105013. */
  105014. _this.PREMULTIPLYALPHA = false;
  105015. /**
  105016. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  105017. */
  105018. _this.USERGBCOLOR = false;
  105019. /**
  105020. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  105021. * stays aligned with the desired configuration.
  105022. */
  105023. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  105024. /**
  105025. * True to add noise in order to reduce the banding effect.
  105026. */
  105027. _this.NOISE = false;
  105028. /**
  105029. * is the reflection texture in BGR color scheme?
  105030. * Mainly used to solve a bug in ios10 video tag
  105031. */
  105032. _this.REFLECTIONBGR = false;
  105033. _this.IMAGEPROCESSING = false;
  105034. _this.VIGNETTE = false;
  105035. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  105036. _this.VIGNETTEBLENDMODEOPAQUE = false;
  105037. _this.TONEMAPPING = false;
  105038. _this.TONEMAPPING_ACES = false;
  105039. _this.CONTRAST = false;
  105040. _this.COLORCURVES = false;
  105041. _this.COLORGRADING = false;
  105042. _this.COLORGRADING3D = false;
  105043. _this.SAMPLER3DGREENDEPTH = false;
  105044. _this.SAMPLER3DBGRMAP = false;
  105045. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  105046. _this.EXPOSURE = false;
  105047. // Reflection.
  105048. _this.REFLECTION = false;
  105049. _this.REFLECTIONMAP_3D = false;
  105050. _this.REFLECTIONMAP_SPHERICAL = false;
  105051. _this.REFLECTIONMAP_PLANAR = false;
  105052. _this.REFLECTIONMAP_CUBIC = false;
  105053. _this.REFLECTIONMAP_PROJECTION = false;
  105054. _this.REFLECTIONMAP_SKYBOX = false;
  105055. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105056. _this.REFLECTIONMAP_EXPLICIT = false;
  105057. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105058. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105059. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105060. _this.INVERTCUBICMAP = false;
  105061. _this.REFLECTIONMAP_OPPOSITEZ = false;
  105062. _this.LODINREFLECTIONALPHA = false;
  105063. _this.GAMMAREFLECTION = false;
  105064. _this.RGBDREFLECTION = false;
  105065. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  105066. // Default BJS.
  105067. _this.MAINUV1 = false;
  105068. _this.MAINUV2 = false;
  105069. _this.UV1 = false;
  105070. _this.UV2 = false;
  105071. _this.CLIPPLANE = false;
  105072. _this.CLIPPLANE2 = false;
  105073. _this.CLIPPLANE3 = false;
  105074. _this.CLIPPLANE4 = false;
  105075. _this.POINTSIZE = false;
  105076. _this.FOG = false;
  105077. _this.NORMAL = false;
  105078. _this.NUM_BONE_INFLUENCERS = 0;
  105079. _this.BonesPerMesh = 0;
  105080. _this.INSTANCES = false;
  105081. _this.SHADOWFLOAT = false;
  105082. _this.rebuild();
  105083. return _this;
  105084. }
  105085. return BackgroundMaterialDefines;
  105086. }(BABYLON.MaterialDefines));
  105087. /**
  105088. * Background material used to create an efficient environement around your scene.
  105089. */
  105090. var BackgroundMaterial = /** @class */ (function (_super) {
  105091. __extends(BackgroundMaterial, _super);
  105092. /**
  105093. * Instantiates a Background Material in the given scene
  105094. * @param name The friendly name of the material
  105095. * @param scene The scene to add the material to
  105096. */
  105097. function BackgroundMaterial(name, scene) {
  105098. var _this = _super.call(this, name, scene) || this;
  105099. /**
  105100. * Key light Color (multiply against the environement texture)
  105101. */
  105102. _this.primaryColor = BABYLON.Color3.White();
  105103. _this._primaryColorShadowLevel = 0;
  105104. _this._primaryColorHighlightLevel = 0;
  105105. /**
  105106. * Reflection Texture used in the material.
  105107. * Should be author in a specific way for the best result (refer to the documentation).
  105108. */
  105109. _this.reflectionTexture = null;
  105110. /**
  105111. * Reflection Texture level of blur.
  105112. *
  105113. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  105114. * texture twice.
  105115. */
  105116. _this.reflectionBlur = 0;
  105117. /**
  105118. * Diffuse Texture used in the material.
  105119. * Should be author in a specific way for the best result (refer to the documentation).
  105120. */
  105121. _this.diffuseTexture = null;
  105122. _this._shadowLights = null;
  105123. /**
  105124. * Specify the list of lights casting shadow on the material.
  105125. * All scene shadow lights will be included if null.
  105126. */
  105127. _this.shadowLights = null;
  105128. /**
  105129. * Helps adjusting the shadow to a softer level if required.
  105130. * 0 means black shadows and 1 means no shadows.
  105131. */
  105132. _this.shadowLevel = 0;
  105133. /**
  105134. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  105135. * It is usually zero but might be interesting to modify according to your setup.
  105136. */
  105137. _this.sceneCenter = BABYLON.Vector3.Zero();
  105138. /**
  105139. * This helps specifying that the material is falling off to the sky box at grazing angle.
  105140. * This helps ensuring a nice transition when the camera goes under the ground.
  105141. */
  105142. _this.opacityFresnel = true;
  105143. /**
  105144. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  105145. * This helps adding a mirror texture on the ground.
  105146. */
  105147. _this.reflectionFresnel = false;
  105148. /**
  105149. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  105150. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  105151. */
  105152. _this.reflectionFalloffDistance = 0.0;
  105153. /**
  105154. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  105155. */
  105156. _this.reflectionAmount = 1.0;
  105157. /**
  105158. * This specifies the weight of the reflection at grazing angle.
  105159. */
  105160. _this.reflectionReflectance0 = 0.05;
  105161. /**
  105162. * This specifies the weight of the reflection at a perpendicular point of view.
  105163. */
  105164. _this.reflectionReflectance90 = 0.5;
  105165. /**
  105166. * Helps to directly use the maps channels instead of their level.
  105167. */
  105168. _this.useRGBColor = true;
  105169. /**
  105170. * This helps reducing the banding effect that could occur on the background.
  105171. */
  105172. _this.enableNoise = false;
  105173. _this._fovMultiplier = 1.0;
  105174. /**
  105175. * Enable the FOV adjustment feature controlled by fovMultiplier.
  105176. */
  105177. _this.useEquirectangularFOV = false;
  105178. _this._maxSimultaneousLights = 4;
  105179. /**
  105180. * Number of Simultaneous lights allowed on the material.
  105181. */
  105182. _this.maxSimultaneousLights = 4;
  105183. /**
  105184. * Keep track of the image processing observer to allow dispose and replace.
  105185. */
  105186. _this._imageProcessingObserver = null;
  105187. /**
  105188. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  105189. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  105190. */
  105191. _this.switchToBGR = false;
  105192. // Temp values kept as cache in the material.
  105193. _this._renderTargets = new BABYLON.SmartArray(16);
  105194. _this._reflectionControls = BABYLON.Vector4.Zero();
  105195. _this._white = BABYLON.Color3.White();
  105196. _this._primaryShadowColor = BABYLON.Color3.Black();
  105197. _this._primaryHighlightColor = BABYLON.Color3.Black();
  105198. // Setup the default processing configuration to the scene.
  105199. _this._attachImageProcessingConfiguration(null);
  105200. _this.getRenderTargetTextures = function () {
  105201. _this._renderTargets.reset();
  105202. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  105203. _this._renderTargets.push(_this._diffuseTexture);
  105204. }
  105205. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  105206. _this._renderTargets.push(_this._reflectionTexture);
  105207. }
  105208. return _this._renderTargets;
  105209. };
  105210. return _this;
  105211. }
  105212. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  105213. /**
  105214. * Experimental Internal Use Only.
  105215. *
  105216. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  105217. * This acts as a helper to set the primary color to a more "human friendly" value.
  105218. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  105219. * output color as close as possible from the chosen value.
  105220. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  105221. * part of lighting setup.)
  105222. */
  105223. get: function () {
  105224. return this.__perceptualColor;
  105225. },
  105226. set: function (value) {
  105227. this.__perceptualColor = value;
  105228. this._computePrimaryColorFromPerceptualColor();
  105229. this._markAllSubMeshesAsLightsDirty();
  105230. },
  105231. enumerable: true,
  105232. configurable: true
  105233. });
  105234. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  105235. /**
  105236. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  105237. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  105238. */
  105239. get: function () {
  105240. return this._primaryColorShadowLevel;
  105241. },
  105242. set: function (value) {
  105243. this._primaryColorShadowLevel = value;
  105244. this._computePrimaryColors();
  105245. this._markAllSubMeshesAsLightsDirty();
  105246. },
  105247. enumerable: true,
  105248. configurable: true
  105249. });
  105250. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  105251. /**
  105252. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  105253. * The primary color is used at the level chosen to define what the white area would look.
  105254. */
  105255. get: function () {
  105256. return this._primaryColorHighlightLevel;
  105257. },
  105258. set: function (value) {
  105259. this._primaryColorHighlightLevel = value;
  105260. this._computePrimaryColors();
  105261. this._markAllSubMeshesAsLightsDirty();
  105262. },
  105263. enumerable: true,
  105264. configurable: true
  105265. });
  105266. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  105267. /**
  105268. * Sets the reflection reflectance fresnel values according to the default standard
  105269. * empirically know to work well :-)
  105270. */
  105271. set: function (value) {
  105272. var reflectionWeight = value;
  105273. if (reflectionWeight < 0.5) {
  105274. reflectionWeight = reflectionWeight * 2.0;
  105275. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  105276. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  105277. }
  105278. else {
  105279. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  105280. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  105281. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  105282. }
  105283. },
  105284. enumerable: true,
  105285. configurable: true
  105286. });
  105287. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  105288. /**
  105289. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105290. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  105291. * Recommended to be keep at 1.0 except for special cases.
  105292. */
  105293. get: function () {
  105294. return this._fovMultiplier;
  105295. },
  105296. set: function (value) {
  105297. if (isNaN(value)) {
  105298. value = 1.0;
  105299. }
  105300. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  105301. },
  105302. enumerable: true,
  105303. configurable: true
  105304. });
  105305. /**
  105306. * Attaches a new image processing configuration to the PBR Material.
  105307. * @param configuration (if null the scene configuration will be use)
  105308. */
  105309. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  105310. var _this = this;
  105311. if (configuration === this._imageProcessingConfiguration) {
  105312. return;
  105313. }
  105314. // Detaches observer.
  105315. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105316. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105317. }
  105318. // Pick the scene configuration if needed.
  105319. if (!configuration) {
  105320. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  105321. }
  105322. else {
  105323. this._imageProcessingConfiguration = configuration;
  105324. }
  105325. // Attaches observer.
  105326. if (this._imageProcessingConfiguration) {
  105327. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  105328. _this._computePrimaryColorFromPerceptualColor();
  105329. _this._markAllSubMeshesAsImageProcessingDirty();
  105330. });
  105331. }
  105332. };
  105333. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  105334. /**
  105335. * Gets the image processing configuration used either in this material.
  105336. */
  105337. get: function () {
  105338. return this._imageProcessingConfiguration;
  105339. },
  105340. /**
  105341. * Sets the Default image processing configuration used either in the this material.
  105342. *
  105343. * If sets to null, the scene one is in use.
  105344. */
  105345. set: function (value) {
  105346. this._attachImageProcessingConfiguration(value);
  105347. // Ensure the effect will be rebuilt.
  105348. this._markAllSubMeshesAsTexturesDirty();
  105349. },
  105350. enumerable: true,
  105351. configurable: true
  105352. });
  105353. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  105354. /**
  105355. * Gets wether the color curves effect is enabled.
  105356. */
  105357. get: function () {
  105358. return this.imageProcessingConfiguration.colorCurvesEnabled;
  105359. },
  105360. /**
  105361. * Sets wether the color curves effect is enabled.
  105362. */
  105363. set: function (value) {
  105364. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  105365. },
  105366. enumerable: true,
  105367. configurable: true
  105368. });
  105369. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  105370. /**
  105371. * Gets wether the color grading effect is enabled.
  105372. */
  105373. get: function () {
  105374. return this.imageProcessingConfiguration.colorGradingEnabled;
  105375. },
  105376. /**
  105377. * Gets wether the color grading effect is enabled.
  105378. */
  105379. set: function (value) {
  105380. this.imageProcessingConfiguration.colorGradingEnabled = value;
  105381. },
  105382. enumerable: true,
  105383. configurable: true
  105384. });
  105385. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  105386. /**
  105387. * Gets wether tonemapping is enabled or not.
  105388. */
  105389. get: function () {
  105390. return this._imageProcessingConfiguration.toneMappingEnabled;
  105391. },
  105392. /**
  105393. * Sets wether tonemapping is enabled or not
  105394. */
  105395. set: function (value) {
  105396. this._imageProcessingConfiguration.toneMappingEnabled = value;
  105397. },
  105398. enumerable: true,
  105399. configurable: true
  105400. });
  105401. ;
  105402. ;
  105403. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  105404. /**
  105405. * The camera exposure used on this material.
  105406. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105407. * This corresponds to a photographic exposure.
  105408. */
  105409. get: function () {
  105410. return this._imageProcessingConfiguration.exposure;
  105411. },
  105412. /**
  105413. * The camera exposure used on this material.
  105414. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  105415. * This corresponds to a photographic exposure.
  105416. */
  105417. set: function (value) {
  105418. this._imageProcessingConfiguration.exposure = value;
  105419. },
  105420. enumerable: true,
  105421. configurable: true
  105422. });
  105423. ;
  105424. ;
  105425. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  105426. /**
  105427. * Gets The camera contrast used on this material.
  105428. */
  105429. get: function () {
  105430. return this._imageProcessingConfiguration.contrast;
  105431. },
  105432. /**
  105433. * Sets The camera contrast used on this material.
  105434. */
  105435. set: function (value) {
  105436. this._imageProcessingConfiguration.contrast = value;
  105437. },
  105438. enumerable: true,
  105439. configurable: true
  105440. });
  105441. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  105442. /**
  105443. * Gets the Color Grading 2D Lookup Texture.
  105444. */
  105445. get: function () {
  105446. return this._imageProcessingConfiguration.colorGradingTexture;
  105447. },
  105448. /**
  105449. * Sets the Color Grading 2D Lookup Texture.
  105450. */
  105451. set: function (value) {
  105452. this.imageProcessingConfiguration.colorGradingTexture = value;
  105453. },
  105454. enumerable: true,
  105455. configurable: true
  105456. });
  105457. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  105458. /**
  105459. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105460. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105461. * 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;
  105462. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105463. */
  105464. get: function () {
  105465. return this.imageProcessingConfiguration.colorCurves;
  105466. },
  105467. /**
  105468. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  105469. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  105470. * 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;
  105471. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  105472. */
  105473. set: function (value) {
  105474. this.imageProcessingConfiguration.colorCurves = value;
  105475. },
  105476. enumerable: true,
  105477. configurable: true
  105478. });
  105479. /**
  105480. * The entire material has been created in order to prevent overdraw.
  105481. * @returns false
  105482. */
  105483. BackgroundMaterial.prototype.needAlphaTesting = function () {
  105484. return true;
  105485. };
  105486. /**
  105487. * The entire material has been created in order to prevent overdraw.
  105488. * @returns true if blending is enable
  105489. */
  105490. BackgroundMaterial.prototype.needAlphaBlending = function () {
  105491. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  105492. };
  105493. /**
  105494. * Checks wether the material is ready to be rendered for a given mesh.
  105495. * @param mesh The mesh to render
  105496. * @param subMesh The submesh to check against
  105497. * @param useInstances Specify wether or not the material is used with instances
  105498. * @returns true if all the dependencies are ready (Textures, Effects...)
  105499. */
  105500. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  105501. var _this = this;
  105502. if (useInstances === void 0) { useInstances = false; }
  105503. if (subMesh.effect && this.isFrozen) {
  105504. if (this._wasPreviouslyReady) {
  105505. return true;
  105506. }
  105507. }
  105508. if (!subMesh._materialDefines) {
  105509. subMesh._materialDefines = new BackgroundMaterialDefines();
  105510. }
  105511. var scene = this.getScene();
  105512. var defines = subMesh._materialDefines;
  105513. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  105514. if (defines._renderId === scene.getRenderId()) {
  105515. return true;
  105516. }
  105517. }
  105518. var engine = scene.getEngine();
  105519. // Lights
  105520. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  105521. defines._needNormals = true;
  105522. // Textures
  105523. if (defines._areTexturesDirty) {
  105524. defines._needUVs = false;
  105525. if (scene.texturesEnabled) {
  105526. if (scene.getEngine().getCaps().textureLOD) {
  105527. defines.TEXTURELODSUPPORT = true;
  105528. }
  105529. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105530. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  105531. return false;
  105532. }
  105533. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  105534. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  105535. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  105536. defines.OPACITYFRESNEL = this._opacityFresnel;
  105537. }
  105538. else {
  105539. defines.DIFFUSE = false;
  105540. defines.DIFFUSEHASALPHA = false;
  105541. defines.GAMMADIFFUSE = false;
  105542. defines.OPACITYFRESNEL = false;
  105543. }
  105544. var reflectionTexture = this._reflectionTexture;
  105545. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105546. if (!reflectionTexture.isReadyOrNotBlocking()) {
  105547. return false;
  105548. }
  105549. defines.REFLECTION = true;
  105550. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  105551. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  105552. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  105553. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  105554. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  105555. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  105556. defines.REFLECTIONBGR = this.switchToBGR;
  105557. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  105558. defines.INVERTCUBICMAP = true;
  105559. }
  105560. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  105561. switch (reflectionTexture.coordinatesMode) {
  105562. case BABYLON.Texture.EXPLICIT_MODE:
  105563. defines.REFLECTIONMAP_EXPLICIT = true;
  105564. break;
  105565. case BABYLON.Texture.PLANAR_MODE:
  105566. defines.REFLECTIONMAP_PLANAR = true;
  105567. break;
  105568. case BABYLON.Texture.PROJECTION_MODE:
  105569. defines.REFLECTIONMAP_PROJECTION = true;
  105570. break;
  105571. case BABYLON.Texture.SKYBOX_MODE:
  105572. defines.REFLECTIONMAP_SKYBOX = true;
  105573. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  105574. break;
  105575. case BABYLON.Texture.SPHERICAL_MODE:
  105576. defines.REFLECTIONMAP_SPHERICAL = true;
  105577. break;
  105578. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  105579. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  105580. break;
  105581. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  105582. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  105583. break;
  105584. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  105585. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  105586. break;
  105587. case BABYLON.Texture.CUBIC_MODE:
  105588. case BABYLON.Texture.INVCUBIC_MODE:
  105589. default:
  105590. defines.REFLECTIONMAP_CUBIC = true;
  105591. break;
  105592. }
  105593. if (this.reflectionFresnel) {
  105594. defines.REFLECTIONFRESNEL = true;
  105595. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  105596. this._reflectionControls.x = this.reflectionAmount;
  105597. this._reflectionControls.y = this.reflectionReflectance0;
  105598. this._reflectionControls.z = this.reflectionReflectance90;
  105599. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  105600. }
  105601. else {
  105602. defines.REFLECTIONFRESNEL = false;
  105603. defines.REFLECTIONFALLOFF = false;
  105604. }
  105605. }
  105606. else {
  105607. defines.REFLECTION = false;
  105608. defines.REFLECTIONFRESNEL = false;
  105609. defines.REFLECTIONFALLOFF = false;
  105610. defines.REFLECTIONBLUR = false;
  105611. defines.REFLECTIONMAP_3D = false;
  105612. defines.REFLECTIONMAP_SPHERICAL = false;
  105613. defines.REFLECTIONMAP_PLANAR = false;
  105614. defines.REFLECTIONMAP_CUBIC = false;
  105615. defines.REFLECTIONMAP_PROJECTION = false;
  105616. defines.REFLECTIONMAP_SKYBOX = false;
  105617. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  105618. defines.REFLECTIONMAP_EXPLICIT = false;
  105619. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  105620. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  105621. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  105622. defines.INVERTCUBICMAP = false;
  105623. defines.REFLECTIONMAP_OPPOSITEZ = false;
  105624. defines.LODINREFLECTIONALPHA = false;
  105625. defines.GAMMAREFLECTION = false;
  105626. defines.RGBDREFLECTION = false;
  105627. }
  105628. }
  105629. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  105630. defines.USERGBCOLOR = this._useRGBColor;
  105631. defines.NOISE = this._enableNoise;
  105632. }
  105633. if (defines._areLightsDirty) {
  105634. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  105635. }
  105636. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  105637. if (!this._imageProcessingConfiguration.isReady()) {
  105638. return false;
  105639. }
  105640. this._imageProcessingConfiguration.prepareDefines(defines);
  105641. }
  105642. // Misc.
  105643. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  105644. // Values that need to be evaluated on every frame
  105645. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  105646. // Attribs
  105647. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  105648. if (mesh) {
  105649. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  105650. mesh.createNormals(true);
  105651. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  105652. }
  105653. }
  105654. }
  105655. // Get correct effect
  105656. if (defines.isDirty) {
  105657. defines.markAsProcessed();
  105658. scene.resetCachedMaterial();
  105659. // Fallbacks
  105660. var fallbacks = new BABYLON.EffectFallbacks();
  105661. if (defines.FOG) {
  105662. fallbacks.addFallback(0, "FOG");
  105663. }
  105664. if (defines.POINTSIZE) {
  105665. fallbacks.addFallback(1, "POINTSIZE");
  105666. }
  105667. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  105668. if (defines.NUM_BONE_INFLUENCERS > 0) {
  105669. fallbacks.addCPUSkinningFallback(0, mesh);
  105670. }
  105671. //Attributes
  105672. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105673. if (defines.NORMAL) {
  105674. attribs.push(BABYLON.VertexBuffer.NormalKind);
  105675. }
  105676. if (defines.UV1) {
  105677. attribs.push(BABYLON.VertexBuffer.UVKind);
  105678. }
  105679. if (defines.UV2) {
  105680. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105681. }
  105682. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  105683. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  105684. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  105685. "vFogInfos", "vFogColor", "pointSize",
  105686. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  105687. "vPrimaryColor", "vPrimaryColorShadow",
  105688. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  105689. "shadowLevel", "alpha",
  105690. "vBackgroundCenter", "vReflectionControl",
  105691. "vDiffuseInfos", "diffuseMatrix",
  105692. ];
  105693. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  105694. var uniformBuffers = ["Material", "Scene"];
  105695. if (BABYLON.ImageProcessingConfiguration) {
  105696. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  105697. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  105698. }
  105699. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  105700. uniformsNames: uniforms,
  105701. uniformBuffersNames: uniformBuffers,
  105702. samplers: samplers,
  105703. defines: defines,
  105704. maxSimultaneousLights: this._maxSimultaneousLights
  105705. });
  105706. var onCompiled = function (effect) {
  105707. if (_this.onCompiled) {
  105708. _this.onCompiled(effect);
  105709. }
  105710. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  105711. };
  105712. var join = defines.toString();
  105713. subMesh.setEffect(scene.getEngine().createEffect("background", {
  105714. attributes: attribs,
  105715. uniformsNames: uniforms,
  105716. uniformBuffersNames: uniformBuffers,
  105717. samplers: samplers,
  105718. defines: join,
  105719. fallbacks: fallbacks,
  105720. onCompiled: onCompiled,
  105721. onError: this.onError,
  105722. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  105723. }, engine), defines);
  105724. this.buildUniformLayout();
  105725. }
  105726. if (!subMesh.effect || !subMesh.effect.isReady()) {
  105727. return false;
  105728. }
  105729. defines._renderId = scene.getRenderId();
  105730. this._wasPreviouslyReady = true;
  105731. return true;
  105732. };
  105733. /**
  105734. * Compute the primary color according to the chosen perceptual color.
  105735. */
  105736. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  105737. if (!this.__perceptualColor) {
  105738. return;
  105739. }
  105740. this._primaryColor.copyFrom(this.__perceptualColor);
  105741. // Revert gamma space.
  105742. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  105743. // Revert image processing configuration.
  105744. if (this._imageProcessingConfiguration) {
  105745. // Revert Exposure.
  105746. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  105747. }
  105748. this._computePrimaryColors();
  105749. };
  105750. /**
  105751. * Compute the highlights and shadow colors according to their chosen levels.
  105752. */
  105753. BackgroundMaterial.prototype._computePrimaryColors = function () {
  105754. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  105755. return;
  105756. }
  105757. // Find the highlight color based on the configuration.
  105758. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  105759. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  105760. // Find the shadow color based on the configuration.
  105761. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  105762. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  105763. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  105764. };
  105765. /**
  105766. * Build the uniform buffer used in the material.
  105767. */
  105768. BackgroundMaterial.prototype.buildUniformLayout = function () {
  105769. // Order is important !
  105770. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  105771. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  105772. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  105773. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  105774. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  105775. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  105776. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  105777. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  105778. this._uniformBuffer.addUniform("pointSize", 1);
  105779. this._uniformBuffer.addUniform("shadowLevel", 1);
  105780. this._uniformBuffer.addUniform("alpha", 1);
  105781. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  105782. this._uniformBuffer.addUniform("vReflectionControl", 4);
  105783. this._uniformBuffer.create();
  105784. };
  105785. /**
  105786. * Unbind the material.
  105787. */
  105788. BackgroundMaterial.prototype.unbind = function () {
  105789. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  105790. this._uniformBuffer.setTexture("diffuseSampler", null);
  105791. }
  105792. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  105793. this._uniformBuffer.setTexture("reflectionSampler", null);
  105794. }
  105795. _super.prototype.unbind.call(this);
  105796. };
  105797. /**
  105798. * Bind only the world matrix to the material.
  105799. * @param world The world matrix to bind.
  105800. */
  105801. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  105802. this._activeEffect.setMatrix("world", world);
  105803. };
  105804. /**
  105805. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  105806. * @param world The world matrix to bind.
  105807. * @param subMesh The submesh to bind for.
  105808. */
  105809. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  105810. var scene = this.getScene();
  105811. var defines = subMesh._materialDefines;
  105812. if (!defines) {
  105813. return;
  105814. }
  105815. var effect = subMesh.effect;
  105816. if (!effect) {
  105817. return;
  105818. }
  105819. this._activeEffect = effect;
  105820. // Matrices
  105821. this.bindOnlyWorldMatrix(world);
  105822. // Bones
  105823. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  105824. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  105825. if (mustRebind) {
  105826. this._uniformBuffer.bindToEffect(effect, "Material");
  105827. this.bindViewProjection(effect);
  105828. var reflectionTexture = this._reflectionTexture;
  105829. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  105830. // Texture uniforms
  105831. if (scene.texturesEnabled) {
  105832. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105833. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  105834. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  105835. }
  105836. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105837. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  105838. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  105839. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  105840. }
  105841. }
  105842. if (this.shadowLevel > 0) {
  105843. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  105844. }
  105845. this._uniformBuffer.updateFloat("alpha", this.alpha);
  105846. // Point size
  105847. if (this.pointsCloud) {
  105848. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  105849. }
  105850. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  105851. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  105852. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  105853. }
  105854. else {
  105855. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  105856. }
  105857. }
  105858. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  105859. // Textures
  105860. if (scene.texturesEnabled) {
  105861. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  105862. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  105863. }
  105864. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  105865. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  105866. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105867. }
  105868. else if (!defines.REFLECTIONBLUR) {
  105869. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  105870. }
  105871. else {
  105872. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  105873. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  105874. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  105875. }
  105876. if (defines.REFLECTIONFRESNEL) {
  105877. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  105878. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  105879. }
  105880. }
  105881. }
  105882. // Clip plane
  105883. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  105884. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  105885. }
  105886. if (mustRebind || !this.isFrozen) {
  105887. if (scene.lightsEnabled) {
  105888. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  105889. }
  105890. // View
  105891. this.bindView(effect);
  105892. // Fog
  105893. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  105894. // image processing
  105895. if (this._imageProcessingConfiguration) {
  105896. this._imageProcessingConfiguration.bind(this._activeEffect);
  105897. }
  105898. }
  105899. this._uniformBuffer.update();
  105900. this._afterBind(mesh, this._activeEffect);
  105901. };
  105902. /**
  105903. * Dispose the material.
  105904. * @param forceDisposeEffect Force disposal of the associated effect.
  105905. * @param forceDisposeTextures Force disposal of the associated textures.
  105906. */
  105907. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  105908. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  105909. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  105910. if (forceDisposeTextures) {
  105911. if (this.diffuseTexture) {
  105912. this.diffuseTexture.dispose();
  105913. }
  105914. if (this.reflectionTexture) {
  105915. this.reflectionTexture.dispose();
  105916. }
  105917. }
  105918. this._renderTargets.dispose();
  105919. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  105920. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  105921. }
  105922. _super.prototype.dispose.call(this, forceDisposeEffect);
  105923. };
  105924. /**
  105925. * Clones the material.
  105926. * @param name The cloned name.
  105927. * @returns The cloned material.
  105928. */
  105929. BackgroundMaterial.prototype.clone = function (name) {
  105930. var _this = this;
  105931. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  105932. };
  105933. /**
  105934. * Serializes the current material to its JSON representation.
  105935. * @returns The JSON representation.
  105936. */
  105937. BackgroundMaterial.prototype.serialize = function () {
  105938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105939. serializationObject.customType = "BABYLON.BackgroundMaterial";
  105940. return serializationObject;
  105941. };
  105942. /**
  105943. * Gets the class name of the material
  105944. * @returns "BackgroundMaterial"
  105945. */
  105946. BackgroundMaterial.prototype.getClassName = function () {
  105947. return "BackgroundMaterial";
  105948. };
  105949. /**
  105950. * Parse a JSON input to create back a background material.
  105951. * @param source The JSON data to parse
  105952. * @param scene The scene to create the parsed material in
  105953. * @param rootUrl The root url of the assets the material depends upon
  105954. * @returns the instantiated BackgroundMaterial.
  105955. */
  105956. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  105957. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  105958. };
  105959. /**
  105960. * Standard reflectance value at parallel view angle.
  105961. */
  105962. BackgroundMaterial.StandardReflectance0 = 0.05;
  105963. /**
  105964. * Standard reflectance value at grazing angle.
  105965. */
  105966. BackgroundMaterial.StandardReflectance90 = 0.5;
  105967. __decorate([
  105968. BABYLON.serializeAsColor3()
  105969. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  105970. __decorate([
  105971. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105972. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  105973. __decorate([
  105974. BABYLON.serializeAsColor3()
  105975. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  105976. __decorate([
  105977. BABYLON.serialize()
  105978. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  105979. __decorate([
  105980. BABYLON.serialize()
  105981. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  105982. __decorate([
  105983. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  105984. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  105985. __decorate([
  105986. BABYLON.serializeAsTexture()
  105987. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  105988. __decorate([
  105989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105990. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  105991. __decorate([
  105992. BABYLON.serialize()
  105993. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  105994. __decorate([
  105995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105996. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  105997. __decorate([
  105998. BABYLON.serializeAsTexture()
  105999. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  106000. __decorate([
  106001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106002. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  106003. __decorate([
  106004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106005. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  106006. __decorate([
  106007. BABYLON.serialize()
  106008. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  106009. __decorate([
  106010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106011. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  106012. __decorate([
  106013. BABYLON.serializeAsVector3()
  106014. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  106015. __decorate([
  106016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106017. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  106018. __decorate([
  106019. BABYLON.serialize()
  106020. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  106021. __decorate([
  106022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106023. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  106024. __decorate([
  106025. BABYLON.serialize()
  106026. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  106027. __decorate([
  106028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106029. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  106030. __decorate([
  106031. BABYLON.serialize()
  106032. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  106033. __decorate([
  106034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106035. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  106036. __decorate([
  106037. BABYLON.serialize()
  106038. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  106039. __decorate([
  106040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106041. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  106042. __decorate([
  106043. BABYLON.serialize()
  106044. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  106045. __decorate([
  106046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106047. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  106048. __decorate([
  106049. BABYLON.serialize()
  106050. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  106051. __decorate([
  106052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106053. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  106054. __decorate([
  106055. BABYLON.serialize()
  106056. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  106057. __decorate([
  106058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106059. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  106060. __decorate([
  106061. BABYLON.serialize()
  106062. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  106063. __decorate([
  106064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106065. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  106066. __decorate([
  106067. BABYLON.serialize()
  106068. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  106069. __decorate([
  106070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  106071. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  106072. __decorate([
  106073. BABYLON.serializeAsImageProcessingConfiguration()
  106074. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  106075. return BackgroundMaterial;
  106076. }(BABYLON.PushMaterial));
  106077. BABYLON.BackgroundMaterial = BackgroundMaterial;
  106078. })(BABYLON || (BABYLON = {}));
  106079. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  106080. var __assign = (this && this.__assign) || function () {
  106081. __assign = Object.assign || function(t) {
  106082. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106083. s = arguments[i];
  106084. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106085. t[p] = s[p];
  106086. }
  106087. return t;
  106088. };
  106089. return __assign.apply(this, arguments);
  106090. };
  106091. var BABYLON;
  106092. (function (BABYLON) {
  106093. /**
  106094. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  106095. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  106096. * It also helps with the default setup of your imageProcessing configuration.
  106097. */
  106098. var EnvironmentHelper = /** @class */ (function () {
  106099. /**
  106100. * constructor
  106101. * @param options
  106102. * @param scene The scene to add the material to
  106103. */
  106104. function EnvironmentHelper(options, scene) {
  106105. var _this = this;
  106106. this._errorHandler = function (message, exception) {
  106107. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  106108. };
  106109. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  106110. this._scene = scene;
  106111. this.onErrorObservable = new BABYLON.Observable();
  106112. this._setupBackground();
  106113. this._setupImageProcessing();
  106114. }
  106115. /**
  106116. * Creates the default options for the helper.
  106117. */
  106118. EnvironmentHelper._getDefaultOptions = function () {
  106119. return {
  106120. createGround: true,
  106121. groundSize: 15,
  106122. groundTexture: this._groundTextureCDNUrl,
  106123. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106124. groundOpacity: 0.9,
  106125. enableGroundShadow: true,
  106126. groundShadowLevel: 0.5,
  106127. enableGroundMirror: false,
  106128. groundMirrorSizeRatio: 0.3,
  106129. groundMirrorBlurKernel: 64,
  106130. groundMirrorAmount: 1,
  106131. groundMirrorFresnelWeight: 1,
  106132. groundMirrorFallOffDistance: 0,
  106133. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  106134. groundYBias: 0.00001,
  106135. createSkybox: true,
  106136. skyboxSize: 20,
  106137. skyboxTexture: this._skyboxTextureCDNUrl,
  106138. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  106139. backgroundYRotation: 0,
  106140. sizeAuto: true,
  106141. rootPosition: BABYLON.Vector3.Zero(),
  106142. setupImageProcessing: true,
  106143. environmentTexture: this._environmentTextureCDNUrl,
  106144. cameraExposure: 0.8,
  106145. cameraContrast: 1.2,
  106146. toneMappingEnabled: true,
  106147. };
  106148. };
  106149. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  106150. /**
  106151. * Gets the root mesh created by the helper.
  106152. */
  106153. get: function () {
  106154. return this._rootMesh;
  106155. },
  106156. enumerable: true,
  106157. configurable: true
  106158. });
  106159. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  106160. /**
  106161. * Gets the skybox created by the helper.
  106162. */
  106163. get: function () {
  106164. return this._skybox;
  106165. },
  106166. enumerable: true,
  106167. configurable: true
  106168. });
  106169. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  106170. /**
  106171. * Gets the skybox texture created by the helper.
  106172. */
  106173. get: function () {
  106174. return this._skyboxTexture;
  106175. },
  106176. enumerable: true,
  106177. configurable: true
  106178. });
  106179. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  106180. /**
  106181. * Gets the skybox material created by the helper.
  106182. */
  106183. get: function () {
  106184. return this._skyboxMaterial;
  106185. },
  106186. enumerable: true,
  106187. configurable: true
  106188. });
  106189. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  106190. /**
  106191. * Gets the ground mesh created by the helper.
  106192. */
  106193. get: function () {
  106194. return this._ground;
  106195. },
  106196. enumerable: true,
  106197. configurable: true
  106198. });
  106199. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  106200. /**
  106201. * Gets the ground texture created by the helper.
  106202. */
  106203. get: function () {
  106204. return this._groundTexture;
  106205. },
  106206. enumerable: true,
  106207. configurable: true
  106208. });
  106209. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  106210. /**
  106211. * Gets the ground mirror created by the helper.
  106212. */
  106213. get: function () {
  106214. return this._groundMirror;
  106215. },
  106216. enumerable: true,
  106217. configurable: true
  106218. });
  106219. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  106220. /**
  106221. * Gets the ground mirror render list to helps pushing the meshes
  106222. * you wish in the ground reflection.
  106223. */
  106224. get: function () {
  106225. if (this._groundMirror) {
  106226. return this._groundMirror.renderList;
  106227. }
  106228. return null;
  106229. },
  106230. enumerable: true,
  106231. configurable: true
  106232. });
  106233. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  106234. /**
  106235. * Gets the ground material created by the helper.
  106236. */
  106237. get: function () {
  106238. return this._groundMaterial;
  106239. },
  106240. enumerable: true,
  106241. configurable: true
  106242. });
  106243. /**
  106244. * Updates the background according to the new options
  106245. * @param options
  106246. */
  106247. EnvironmentHelper.prototype.updateOptions = function (options) {
  106248. var newOptions = __assign({}, this._options, options);
  106249. if (this._ground && !newOptions.createGround) {
  106250. this._ground.dispose();
  106251. this._ground = null;
  106252. }
  106253. if (this._groundMaterial && !newOptions.createGround) {
  106254. this._groundMaterial.dispose();
  106255. this._groundMaterial = null;
  106256. }
  106257. if (this._groundTexture) {
  106258. if (this._options.groundTexture != newOptions.groundTexture) {
  106259. this._groundTexture.dispose();
  106260. this._groundTexture = null;
  106261. }
  106262. }
  106263. if (this._skybox && !newOptions.createSkybox) {
  106264. this._skybox.dispose();
  106265. this._skybox = null;
  106266. }
  106267. if (this._skyboxMaterial && !newOptions.createSkybox) {
  106268. this._skyboxMaterial.dispose();
  106269. this._skyboxMaterial = null;
  106270. }
  106271. if (this._skyboxTexture) {
  106272. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  106273. this._skyboxTexture.dispose();
  106274. this._skyboxTexture = null;
  106275. }
  106276. }
  106277. if (this._groundMirror && !newOptions.enableGroundMirror) {
  106278. this._groundMirror.dispose();
  106279. this._groundMirror = null;
  106280. }
  106281. if (this._scene.environmentTexture) {
  106282. if (this._options.environmentTexture != newOptions.environmentTexture) {
  106283. this._scene.environmentTexture.dispose();
  106284. }
  106285. }
  106286. this._options = newOptions;
  106287. this._setupBackground();
  106288. this._setupImageProcessing();
  106289. };
  106290. /**
  106291. * Sets the primary color of all the available elements.
  106292. * @param color the main color to affect to the ground and the background
  106293. */
  106294. EnvironmentHelper.prototype.setMainColor = function (color) {
  106295. if (this.groundMaterial) {
  106296. this.groundMaterial.primaryColor = color;
  106297. }
  106298. if (this.skyboxMaterial) {
  106299. this.skyboxMaterial.primaryColor = color;
  106300. }
  106301. if (this.groundMirror) {
  106302. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  106303. }
  106304. };
  106305. /**
  106306. * Setup the image processing according to the specified options.
  106307. */
  106308. EnvironmentHelper.prototype._setupImageProcessing = function () {
  106309. if (this._options.setupImageProcessing) {
  106310. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  106311. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  106312. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  106313. this._setupEnvironmentTexture();
  106314. }
  106315. };
  106316. /**
  106317. * Setup the environment texture according to the specified options.
  106318. */
  106319. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  106320. if (this._scene.environmentTexture) {
  106321. return;
  106322. }
  106323. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  106324. this._scene.environmentTexture = this._options.environmentTexture;
  106325. return;
  106326. }
  106327. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  106328. this._scene.environmentTexture = environmentTexture;
  106329. };
  106330. /**
  106331. * Setup the background according to the specified options.
  106332. */
  106333. EnvironmentHelper.prototype._setupBackground = function () {
  106334. if (!this._rootMesh) {
  106335. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  106336. }
  106337. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  106338. var sceneSize = this._getSceneSize();
  106339. if (this._options.createGround) {
  106340. this._setupGround(sceneSize);
  106341. this._setupGroundMaterial();
  106342. this._setupGroundDiffuseTexture();
  106343. if (this._options.enableGroundMirror) {
  106344. this._setupGroundMirrorTexture(sceneSize);
  106345. }
  106346. this._setupMirrorInGroundMaterial();
  106347. }
  106348. if (this._options.createSkybox) {
  106349. this._setupSkybox(sceneSize);
  106350. this._setupSkyboxMaterial();
  106351. this._setupSkyboxReflectionTexture();
  106352. }
  106353. this._rootMesh.position.x = sceneSize.rootPosition.x;
  106354. this._rootMesh.position.z = sceneSize.rootPosition.z;
  106355. this._rootMesh.position.y = sceneSize.rootPosition.y;
  106356. };
  106357. /**
  106358. * Get the scene sizes according to the setup.
  106359. */
  106360. EnvironmentHelper.prototype._getSceneSize = function () {
  106361. var _this = this;
  106362. var groundSize = this._options.groundSize;
  106363. var skyboxSize = this._options.skyboxSize;
  106364. var rootPosition = this._options.rootPosition;
  106365. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  106366. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106367. }
  106368. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  106369. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  106370. });
  106371. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  106372. if (this._options.sizeAuto) {
  106373. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  106374. this._scene.activeCamera.upperRadiusLimit) {
  106375. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  106376. skyboxSize = groundSize;
  106377. }
  106378. var sceneDiagonalLenght = sceneDiagonal.length();
  106379. if (sceneDiagonalLenght > groundSize) {
  106380. groundSize = sceneDiagonalLenght * 2;
  106381. skyboxSize = groundSize;
  106382. }
  106383. // 10 % bigger.
  106384. groundSize *= 1.1;
  106385. skyboxSize *= 1.5;
  106386. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  106387. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  106388. }
  106389. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  106390. };
  106391. /**
  106392. * Setup the ground according to the specified options.
  106393. */
  106394. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  106395. var _this = this;
  106396. if (!this._ground || this._ground.isDisposed()) {
  106397. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  106398. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  106399. this._ground.parent = this._rootMesh;
  106400. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  106401. }
  106402. this._ground.receiveShadows = this._options.enableGroundShadow;
  106403. };
  106404. /**
  106405. * Setup the ground material according to the specified options.
  106406. */
  106407. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  106408. if (!this._groundMaterial) {
  106409. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  106410. }
  106411. this._groundMaterial.alpha = this._options.groundOpacity;
  106412. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  106413. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  106414. this._groundMaterial.primaryColor = this._options.groundColor;
  106415. this._groundMaterial.useRGBColor = false;
  106416. this._groundMaterial.enableNoise = true;
  106417. if (this._ground) {
  106418. this._ground.material = this._groundMaterial;
  106419. }
  106420. };
  106421. /**
  106422. * Setup the ground diffuse texture according to the specified options.
  106423. */
  106424. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  106425. if (!this._groundMaterial) {
  106426. return;
  106427. }
  106428. if (this._groundTexture) {
  106429. return;
  106430. }
  106431. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  106432. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  106433. return;
  106434. }
  106435. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106436. diffuseTexture.gammaSpace = false;
  106437. diffuseTexture.hasAlpha = true;
  106438. this._groundMaterial.diffuseTexture = diffuseTexture;
  106439. };
  106440. /**
  106441. * Setup the ground mirror texture according to the specified options.
  106442. */
  106443. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  106444. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106445. if (!this._groundMirror) {
  106446. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  106447. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  106448. this._groundMirror.anisotropicFilteringLevel = 1;
  106449. this._groundMirror.wrapU = wrapping;
  106450. this._groundMirror.wrapV = wrapping;
  106451. this._groundMirror.gammaSpace = false;
  106452. if (this._groundMirror.renderList) {
  106453. for (var i = 0; i < this._scene.meshes.length; i++) {
  106454. var mesh = this._scene.meshes[i];
  106455. if (mesh !== this._ground &&
  106456. mesh !== this._skybox &&
  106457. mesh !== this._rootMesh) {
  106458. this._groundMirror.renderList.push(mesh);
  106459. }
  106460. }
  106461. }
  106462. }
  106463. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  106464. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  106465. };
  106466. /**
  106467. * Setup the ground to receive the mirror texture.
  106468. */
  106469. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  106470. if (this._groundMaterial) {
  106471. this._groundMaterial.reflectionTexture = this._groundMirror;
  106472. this._groundMaterial.reflectionFresnel = true;
  106473. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  106474. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  106475. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  106476. }
  106477. };
  106478. /**
  106479. * Setup the skybox according to the specified options.
  106480. */
  106481. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  106482. var _this = this;
  106483. if (!this._skybox || this._skybox.isDisposed()) {
  106484. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  106485. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  106486. }
  106487. this._skybox.parent = this._rootMesh;
  106488. };
  106489. /**
  106490. * Setup the skybox material according to the specified options.
  106491. */
  106492. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  106493. if (!this._skybox) {
  106494. return;
  106495. }
  106496. if (!this._skyboxMaterial) {
  106497. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  106498. }
  106499. this._skyboxMaterial.useRGBColor = false;
  106500. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  106501. this._skyboxMaterial.enableNoise = true;
  106502. this._skybox.material = this._skyboxMaterial;
  106503. };
  106504. /**
  106505. * Setup the skybox reflection texture according to the specified options.
  106506. */
  106507. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  106508. if (!this._skyboxMaterial) {
  106509. return;
  106510. }
  106511. if (this._skyboxTexture) {
  106512. return;
  106513. }
  106514. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  106515. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  106516. return;
  106517. }
  106518. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  106519. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  106520. this._skyboxTexture.gammaSpace = false;
  106521. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  106522. };
  106523. /**
  106524. * Dispose all the elements created by the Helper.
  106525. */
  106526. EnvironmentHelper.prototype.dispose = function () {
  106527. if (this._groundMaterial) {
  106528. this._groundMaterial.dispose(true, true);
  106529. }
  106530. if (this._skyboxMaterial) {
  106531. this._skyboxMaterial.dispose(true, true);
  106532. }
  106533. this._rootMesh.dispose(false);
  106534. };
  106535. /**
  106536. * Default ground texture URL.
  106537. */
  106538. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  106539. /**
  106540. * Default skybox texture URL.
  106541. */
  106542. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  106543. /**
  106544. * Default environment texture URL.
  106545. */
  106546. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  106547. return EnvironmentHelper;
  106548. }());
  106549. BABYLON.EnvironmentHelper = EnvironmentHelper;
  106550. })(BABYLON || (BABYLON = {}));
  106551. //# sourceMappingURL=babylon.environmentHelper.js.map
  106552. var BABYLON;
  106553. (function (BABYLON) {
  106554. /** Internal class used to store shapes for emitters */
  106555. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  106556. function ParticleSystemSetEmitterCreationOptions() {
  106557. }
  106558. return ParticleSystemSetEmitterCreationOptions;
  106559. }());
  106560. /**
  106561. * Represents a set of particle systems working together to create a specific effect
  106562. */
  106563. var ParticleSystemSet = /** @class */ (function () {
  106564. function ParticleSystemSet() {
  106565. /**
  106566. * Gets the particle system list
  106567. */
  106568. this.systems = new Array();
  106569. }
  106570. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  106571. /**
  106572. * Gets the emitter node used with this set
  106573. */
  106574. get: function () {
  106575. return this._emitterNode;
  106576. },
  106577. enumerable: true,
  106578. configurable: true
  106579. });
  106580. /**
  106581. * Creates a new emitter mesh as a sphere
  106582. * @param options defines the options used to create the sphere
  106583. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  106584. * @param scene defines the hosting scene
  106585. */
  106586. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  106587. if (this._emitterNode) {
  106588. this._emitterNode.dispose();
  106589. }
  106590. this._emitterCreationOptions = {
  106591. kind: "Sphere",
  106592. options: options,
  106593. renderingGroupId: renderingGroupId
  106594. };
  106595. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  106596. emitterMesh.renderingGroupId = renderingGroupId;
  106597. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  106598. material.emissiveColor = options.color;
  106599. emitterMesh.material = material;
  106600. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106601. var system = _a[_i];
  106602. system.emitter = emitterMesh;
  106603. }
  106604. this._emitterNode = emitterMesh;
  106605. };
  106606. /**
  106607. * Starts all particle systems of the set
  106608. * @param emitter defines an optional mesh to use as emitter for the particle systems
  106609. */
  106610. ParticleSystemSet.prototype.start = function (emitter) {
  106611. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106612. var system = _a[_i];
  106613. if (emitter) {
  106614. system.emitter = emitter;
  106615. }
  106616. system.start();
  106617. }
  106618. };
  106619. /**
  106620. * Release all associated resources
  106621. */
  106622. ParticleSystemSet.prototype.dispose = function () {
  106623. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106624. var system = _a[_i];
  106625. system.dispose();
  106626. }
  106627. this.systems = [];
  106628. if (this._emitterNode) {
  106629. this._emitterNode.dispose();
  106630. this._emitterNode = null;
  106631. }
  106632. };
  106633. /**
  106634. * Serialize the set into a JSON compatible object
  106635. * @returns a JSON compatible representation of the set
  106636. */
  106637. ParticleSystemSet.prototype.serialize = function () {
  106638. var result = {};
  106639. result.systems = [];
  106640. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  106641. var system = _a[_i];
  106642. result.systems.push(system.serialize());
  106643. }
  106644. if (this._emitterNode) {
  106645. result.emitter = this._emitterCreationOptions;
  106646. }
  106647. return result;
  106648. };
  106649. /**
  106650. * Parse a new ParticleSystemSet from a serialized source
  106651. * @param data defines a JSON compatible representation of the set
  106652. * @param scene defines the hosting scene
  106653. * @param gpu defines if we want GPU particles or CPU particles
  106654. * @returns a new ParticleSystemSet
  106655. */
  106656. ParticleSystemSet.Parse = function (data, scene, gpu) {
  106657. if (gpu === void 0) { gpu = false; }
  106658. var result = new ParticleSystemSet();
  106659. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  106660. scene = scene || BABYLON.Engine.LastCreatedScene;
  106661. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  106662. var system = _a[_i];
  106663. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  106664. }
  106665. if (data.emitter) {
  106666. var options = data.emitter.options;
  106667. switch (data.emitter.kind) {
  106668. case "Sphere":
  106669. result.setEmitterAsSphere({
  106670. diameter: options.diameter,
  106671. segments: options.segments,
  106672. color: BABYLON.Color3.FromArray(options.color)
  106673. }, data.emitter.renderingGroupId, scene);
  106674. break;
  106675. }
  106676. }
  106677. return result;
  106678. };
  106679. return ParticleSystemSet;
  106680. }());
  106681. BABYLON.ParticleSystemSet = ParticleSystemSet;
  106682. })(BABYLON || (BABYLON = {}));
  106683. //# sourceMappingURL=babylon.particleSystemSet.js.map
  106684. var BABYLON;
  106685. (function (BABYLON) {
  106686. /**
  106687. * This class is made for on one-liner static method to help creating particle system set.
  106688. */
  106689. var ParticleHelper = /** @class */ (function () {
  106690. function ParticleHelper() {
  106691. }
  106692. /**
  106693. * Create a default particle system that you can tweak
  106694. * @param emitter defines the emitter to use
  106695. * @param capacity defines the system capacity (default is 500 particles)
  106696. * @param scene defines the hosting scene
  106697. * @returns the new Particle system
  106698. */
  106699. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  106700. if (capacity === void 0) { capacity = 500; }
  106701. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  106702. system.emitter = emitter;
  106703. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  106704. system.createConeEmitter(0.1, Math.PI / 4);
  106705. // Particle color
  106706. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106707. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  106708. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  106709. // Particle Size
  106710. system.minSize = 0.1;
  106711. system.maxSize = 0.1;
  106712. // Emission speed
  106713. system.minEmitPower = 2;
  106714. system.maxEmitPower = 2;
  106715. // Update speed
  106716. system.updateSpeed = 1 / 60;
  106717. system.emitRate = 30;
  106718. return system;
  106719. };
  106720. /**
  106721. * This is the main static method (one-liner) of this helper to create different particle systems
  106722. * @param type This string represents the type to the particle system to create
  106723. * @param scene The scene where the particle system should live
  106724. * @param gpu If the system will use gpu
  106725. * @returns the ParticleSystemSet created
  106726. */
  106727. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  106728. if (gpu === void 0) { gpu = false; }
  106729. if (!scene) {
  106730. scene = BABYLON.Engine.LastCreatedScene;
  106731. ;
  106732. }
  106733. var token = {};
  106734. scene._addPendingData(token);
  106735. return new Promise(function (resolve, reject) {
  106736. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  106737. scene._removePendingData(token);
  106738. return reject("Particle system with GPU is not supported.");
  106739. }
  106740. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  106741. scene._removePendingData(token);
  106742. var newData = JSON.parse(data.toString());
  106743. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  106744. }, undefined, undefined, undefined, function (req, exception) {
  106745. scene._removePendingData(token);
  106746. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  106747. });
  106748. });
  106749. };
  106750. /**
  106751. * Static function used to export a particle system to a ParticleSystemSet variable.
  106752. * Please note that the emitter shape is not exported
  106753. * @param system defines the particle systems to export
  106754. */
  106755. ParticleHelper.ExportSet = function (systems) {
  106756. var set = new BABYLON.ParticleSystemSet();
  106757. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  106758. var system = systems_1[_i];
  106759. set.systems.push(system);
  106760. }
  106761. return set;
  106762. };
  106763. /**
  106764. * Gets or sets base Assets URL
  106765. */
  106766. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  106767. return ParticleHelper;
  106768. }());
  106769. BABYLON.ParticleHelper = ParticleHelper;
  106770. })(BABYLON || (BABYLON = {}));
  106771. //# sourceMappingURL=babylon.particleHelper.js.map
  106772. var BABYLON;
  106773. (function (BABYLON) {
  106774. /**
  106775. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  106776. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  106777. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  106778. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106779. */
  106780. var VideoDome = /** @class */ (function (_super) {
  106781. __extends(VideoDome, _super);
  106782. /**
  106783. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  106784. * @param name Element's name, child elements will append suffixes for their own names.
  106785. * @param urlsOrVideo defines the url(s) or the video element to use
  106786. * @param options An object containing optional or exposed sub element properties
  106787. */
  106788. function VideoDome(name, urlsOrVideo, options, scene) {
  106789. var _this = _super.call(this, name, scene) || this;
  106790. _this._useDirectMapping = false;
  106791. // set defaults and manage values
  106792. name = name || "videoDome";
  106793. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106794. options.clickToPlay = Boolean(options.clickToPlay);
  106795. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  106796. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  106797. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106798. if (options.useDirectMapping === undefined) {
  106799. _this._useDirectMapping = true;
  106800. }
  106801. else {
  106802. _this._useDirectMapping = options.useDirectMapping;
  106803. }
  106804. _this._setReady(false);
  106805. // create
  106806. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  106807. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106808. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  106809. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106810. texture.onLoadObservable.addOnce(function () {
  106811. _this._setReady(true);
  106812. });
  106813. // configure material
  106814. material.useEquirectangularFOV = true;
  106815. material.fovMultiplier = 1.0;
  106816. material.opacityFresnel = false;
  106817. if (_this._useDirectMapping) {
  106818. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106819. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106820. material.diffuseTexture = texture;
  106821. }
  106822. else {
  106823. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106824. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106825. material.reflectionTexture = texture;
  106826. }
  106827. // configure mesh
  106828. _this._mesh.material = material;
  106829. _this._mesh.parent = _this;
  106830. // optional configuration
  106831. if (options.clickToPlay) {
  106832. scene.onPointerUp = function () {
  106833. _this._videoTexture.video.play();
  106834. };
  106835. }
  106836. return _this;
  106837. }
  106838. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  106839. /**
  106840. * Gets the video texture being displayed on the sphere
  106841. */
  106842. get: function () {
  106843. return this._videoTexture;
  106844. },
  106845. enumerable: true,
  106846. configurable: true
  106847. });
  106848. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  106849. /**
  106850. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106851. * Also see the options.resolution property.
  106852. */
  106853. get: function () {
  106854. return this._material.fovMultiplier;
  106855. },
  106856. set: function (value) {
  106857. this._material.fovMultiplier = value;
  106858. },
  106859. enumerable: true,
  106860. configurable: true
  106861. });
  106862. /**
  106863. * Releases resources associated with this node.
  106864. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106865. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106866. */
  106867. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106868. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106869. this._videoTexture.dispose();
  106870. this._mesh.dispose();
  106871. this._material.dispose();
  106872. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106873. };
  106874. return VideoDome;
  106875. }(BABYLON.TransformNode));
  106876. BABYLON.VideoDome = VideoDome;
  106877. })(BABYLON || (BABYLON = {}));
  106878. //# sourceMappingURL=babylon.videoDome.js.map
  106879. var BABYLON;
  106880. (function (BABYLON) {
  106881. /**
  106882. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  106883. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  106884. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  106885. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  106886. */
  106887. var PhotoDome = /** @class */ (function (_super) {
  106888. __extends(PhotoDome, _super);
  106889. /**
  106890. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  106891. * @param name Element's name, child elements will append suffixes for their own names.
  106892. * @param urlsOfPhoto defines the url of the photo to display
  106893. * @param options defines an object containing optional or exposed sub element properties
  106894. * @param onError defines a callback called when an error occured while loading the texture
  106895. */
  106896. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  106897. if (onError === void 0) { onError = null; }
  106898. var _this = _super.call(this, name, scene) || this;
  106899. _this._useDirectMapping = false;
  106900. /**
  106901. * Observable raised when an error occured while loading the 360 image
  106902. */
  106903. _this.onLoadErrorObservable = new BABYLON.Observable();
  106904. // set defaults and manage values
  106905. name = name || "photoDome";
  106906. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  106907. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  106908. if (options.useDirectMapping === undefined) {
  106909. _this._useDirectMapping = true;
  106910. }
  106911. else {
  106912. _this._useDirectMapping = options.useDirectMapping;
  106913. }
  106914. _this._setReady(false);
  106915. // create
  106916. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  106917. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  106918. // configure material
  106919. material.opacityFresnel = false;
  106920. material.useEquirectangularFOV = true;
  106921. material.fovMultiplier = 1.0;
  106922. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  106923. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  106924. if (onError) {
  106925. onError(message, exception);
  106926. }
  106927. });
  106928. _this.photoTexture.onLoadObservable.addOnce(function () {
  106929. _this._setReady(true);
  106930. });
  106931. // configure mesh
  106932. _this._mesh.material = material;
  106933. _this._mesh.parent = _this;
  106934. return _this;
  106935. }
  106936. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  106937. /**
  106938. * Gets or sets the texture being displayed on the sphere
  106939. */
  106940. get: function () {
  106941. return this._photoTexture;
  106942. },
  106943. set: function (value) {
  106944. if (this._photoTexture === value) {
  106945. return;
  106946. }
  106947. this._photoTexture = value;
  106948. if (this._useDirectMapping) {
  106949. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106950. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106951. this._material.diffuseTexture = this._photoTexture;
  106952. }
  106953. else {
  106954. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  106955. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106956. this._material.reflectionTexture = this._photoTexture;
  106957. }
  106958. },
  106959. enumerable: true,
  106960. configurable: true
  106961. });
  106962. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  106963. /**
  106964. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106965. * Also see the options.resolution property.
  106966. */
  106967. get: function () {
  106968. return this._material.fovMultiplier;
  106969. },
  106970. set: function (value) {
  106971. this._material.fovMultiplier = value;
  106972. },
  106973. enumerable: true,
  106974. configurable: true
  106975. });
  106976. /**
  106977. * Releases resources associated with this node.
  106978. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  106979. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  106980. */
  106981. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  106982. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  106983. this._photoTexture.dispose();
  106984. this._mesh.dispose();
  106985. this._material.dispose();
  106986. this.onLoadErrorObservable.clear();
  106987. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  106988. };
  106989. return PhotoDome;
  106990. }(BABYLON.TransformNode));
  106991. BABYLON.PhotoDome = PhotoDome;
  106992. })(BABYLON || (BABYLON = {}));
  106993. //# sourceMappingURL=babylon.photoDome.js.map
  106994. var BABYLON;
  106995. (function (BABYLON) {
  106996. BABYLON.Engine.prototype.createQuery = function () {
  106997. return this._gl.createQuery();
  106998. };
  106999. BABYLON.Engine.prototype.deleteQuery = function (query) {
  107000. this._gl.deleteQuery(query);
  107001. return this;
  107002. };
  107003. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  107004. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  107005. };
  107006. BABYLON.Engine.prototype.getQueryResult = function (query) {
  107007. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  107008. };
  107009. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  107010. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107011. this._gl.beginQuery(glAlgorithm, query);
  107012. return this;
  107013. };
  107014. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  107015. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  107016. this._gl.endQuery(glAlgorithm);
  107017. return this;
  107018. };
  107019. BABYLON.Engine.prototype._createTimeQuery = function () {
  107020. var timerQuery = this.getCaps().timerQuery;
  107021. if (timerQuery.createQueryEXT) {
  107022. return timerQuery.createQueryEXT();
  107023. }
  107024. return this.createQuery();
  107025. };
  107026. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  107027. var timerQuery = this.getCaps().timerQuery;
  107028. if (timerQuery.deleteQueryEXT) {
  107029. timerQuery.deleteQueryEXT(query);
  107030. return;
  107031. }
  107032. this.deleteQuery(query);
  107033. };
  107034. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  107035. var timerQuery = this.getCaps().timerQuery;
  107036. if (timerQuery.getQueryObjectEXT) {
  107037. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  107038. }
  107039. return this.getQueryResult(query);
  107040. };
  107041. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  107042. var timerQuery = this.getCaps().timerQuery;
  107043. if (timerQuery.getQueryObjectEXT) {
  107044. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  107045. }
  107046. return this.isQueryResultAvailable(query);
  107047. };
  107048. BABYLON.Engine.prototype.startTimeQuery = function () {
  107049. var caps = this.getCaps();
  107050. var timerQuery = caps.timerQuery;
  107051. if (!timerQuery) {
  107052. return null;
  107053. }
  107054. var token = new BABYLON._TimeToken();
  107055. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107056. if (caps.canUseTimestampForTimerQuery) {
  107057. token._startTimeQuery = this._createTimeQuery();
  107058. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  107059. }
  107060. else {
  107061. if (this._currentNonTimestampToken) {
  107062. return this._currentNonTimestampToken;
  107063. }
  107064. token._timeElapsedQuery = this._createTimeQuery();
  107065. if (timerQuery.beginQueryEXT) {
  107066. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107067. }
  107068. else {
  107069. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  107070. }
  107071. this._currentNonTimestampToken = token;
  107072. }
  107073. return token;
  107074. };
  107075. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  107076. var caps = this.getCaps();
  107077. var timerQuery = caps.timerQuery;
  107078. if (!timerQuery || !token) {
  107079. return -1;
  107080. }
  107081. if (caps.canUseTimestampForTimerQuery) {
  107082. if (!token._startTimeQuery) {
  107083. return -1;
  107084. }
  107085. if (!token._endTimeQuery) {
  107086. token._endTimeQuery = this._createTimeQuery();
  107087. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  107088. }
  107089. }
  107090. else if (!token._timeElapsedQueryEnded) {
  107091. if (!token._timeElapsedQuery) {
  107092. return -1;
  107093. }
  107094. if (timerQuery.endQueryEXT) {
  107095. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  107096. }
  107097. else {
  107098. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  107099. }
  107100. token._timeElapsedQueryEnded = true;
  107101. }
  107102. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  107103. var available = false;
  107104. if (token._endTimeQuery) {
  107105. available = this._getTimeQueryAvailability(token._endTimeQuery);
  107106. }
  107107. else if (token._timeElapsedQuery) {
  107108. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  107109. }
  107110. if (available && !disjoint) {
  107111. var result = 0;
  107112. if (caps.canUseTimestampForTimerQuery) {
  107113. if (!token._startTimeQuery || !token._endTimeQuery) {
  107114. return -1;
  107115. }
  107116. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  107117. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  107118. result = timeEnd - timeStart;
  107119. this._deleteTimeQuery(token._startTimeQuery);
  107120. this._deleteTimeQuery(token._endTimeQuery);
  107121. token._startTimeQuery = null;
  107122. token._endTimeQuery = null;
  107123. }
  107124. else {
  107125. if (!token._timeElapsedQuery) {
  107126. return -1;
  107127. }
  107128. result = this._getTimeQueryResult(token._timeElapsedQuery);
  107129. this._deleteTimeQuery(token._timeElapsedQuery);
  107130. token._timeElapsedQuery = null;
  107131. token._timeElapsedQueryEnded = false;
  107132. this._currentNonTimestampToken = null;
  107133. }
  107134. return result;
  107135. }
  107136. return -1;
  107137. };
  107138. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  107139. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  107140. };
  107141. // We also need to update AbstractMesh as there is a portion of the code there
  107142. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  107143. var engine = this.getEngine();
  107144. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  107145. this._isOccluded = false;
  107146. return;
  107147. }
  107148. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  107149. this._isOccluded = false;
  107150. return;
  107151. }
  107152. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  107153. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  107154. if (isOcclusionQueryAvailable) {
  107155. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  107156. this._isOcclusionQueryInProgress = false;
  107157. this._occlusionInternalRetryCounter = 0;
  107158. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  107159. }
  107160. else {
  107161. this._occlusionInternalRetryCounter++;
  107162. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  107163. this._isOcclusionQueryInProgress = false;
  107164. this._occlusionInternalRetryCounter = 0;
  107165. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  107166. // if strict continue the last state of the object.
  107167. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  107168. }
  107169. else {
  107170. return;
  107171. }
  107172. }
  107173. }
  107174. var scene = this.getScene();
  107175. if (scene.getBoundingBoxRenderer) {
  107176. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  107177. if (!this._occlusionQuery) {
  107178. this._occlusionQuery = engine.createQuery();
  107179. }
  107180. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  107181. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  107182. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  107183. this._isOcclusionQueryInProgress = true;
  107184. }
  107185. };
  107186. })(BABYLON || (BABYLON = {}));
  107187. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  107188. var BABYLON;
  107189. (function (BABYLON) {
  107190. /**
  107191. * Class used to generate noise procedural textures
  107192. */
  107193. var NoiseProceduralTexture = /** @class */ (function (_super) {
  107194. __extends(NoiseProceduralTexture, _super);
  107195. /**
  107196. * Creates a new NoiseProceduralTexture
  107197. * @param name defines the name fo the texture
  107198. * @param size defines the size of the texture (default is 256)
  107199. * @param scene defines the hosting scene
  107200. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  107201. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  107202. */
  107203. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  107204. if (size === void 0) { size = 256; }
  107205. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  107206. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  107207. _this._time = 0;
  107208. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  107209. _this.brightness = 0.2;
  107210. /** Defines the number of octaves to process */
  107211. _this.octaves = 3;
  107212. /** Defines the level of persistence (0.8 by default) */
  107213. _this.persistence = 0.8;
  107214. /** Gets or sets animation speed factor (default is 1) */
  107215. _this.animationSpeedFactor = 1;
  107216. _this._updateShaderUniforms();
  107217. return _this;
  107218. }
  107219. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  107220. var scene = this.getScene();
  107221. if (!scene) {
  107222. return;
  107223. }
  107224. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  107225. this.setFloat("brightness", this.brightness);
  107226. this.setInt("octaves", this.octaves);
  107227. this.setFloat("persistence", this.persistence);
  107228. this.setFloat("timeScale", this._time);
  107229. };
  107230. /** Generate the current state of the procedural texture */
  107231. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  107232. this._updateShaderUniforms();
  107233. _super.prototype.render.call(this, useCameraPostProcess);
  107234. };
  107235. /**
  107236. * Serializes this noise procedural texture
  107237. * @returns a serialized noise procedural texture object
  107238. */
  107239. NoiseProceduralTexture.prototype.serialize = function () {
  107240. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  107241. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  107242. return serializationObject;
  107243. };
  107244. /**
  107245. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  107246. * @param parsedTexture defines parsed texture data
  107247. * @param scene defines the current scene
  107248. * @param rootUrl defines the root URL containing noise procedural texture information
  107249. * @returns a parsed NoiseProceduralTexture
  107250. */
  107251. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  107252. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  107253. return texture;
  107254. };
  107255. return NoiseProceduralTexture;
  107256. }(BABYLON.ProceduralTexture));
  107257. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  107258. })(BABYLON || (BABYLON = {}));
  107259. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  107260. var __assign = (this && this.__assign) || function () {
  107261. __assign = Object.assign || function(t) {
  107262. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107263. s = arguments[i];
  107264. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107265. t[p] = s[p];
  107266. }
  107267. return t;
  107268. };
  107269. return __assign.apply(this, arguments);
  107270. };
  107271. var BABYLON;
  107272. (function (BABYLON) {
  107273. /**
  107274. * This can helps recording videos from BabylonJS.
  107275. * This is based on the available WebRTC functionalities of the browser.
  107276. *
  107277. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  107278. */
  107279. var VideoRecorder = /** @class */ (function () {
  107280. /**
  107281. * Create a new VideoCapture object which can help converting what you see in Babylon to
  107282. * a video file.
  107283. * @param engine Defines the BabylonJS Engine you wish to record
  107284. * @param options Defines options that can be used to customized the capture
  107285. */
  107286. function VideoRecorder(engine, options) {
  107287. if (options === void 0) { options = null; }
  107288. if (!VideoRecorder.IsSupported(engine)) {
  107289. throw "Your browser does not support recording so far.";
  107290. }
  107291. var canvas = engine.getRenderingCanvas();
  107292. if (!canvas) {
  107293. throw "The babylon engine must have a canvas to be recorded";
  107294. }
  107295. this._canvas = canvas;
  107296. this._canvas.isRecording = false;
  107297. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  107298. var stream = this._canvas.captureStream(this._options.fps);
  107299. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  107300. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  107301. this._mediaRecorder.onerror = this._handleError.bind(this);
  107302. this._mediaRecorder.onstop = this._handleStop.bind(this);
  107303. }
  107304. /**
  107305. * Returns wehther or not the VideoRecorder is available in your browser.
  107306. * @param engine Defines the Babylon Engine to check the support for
  107307. * @returns true if supported otherwise false
  107308. */
  107309. VideoRecorder.IsSupported = function (engine) {
  107310. var canvas = engine.getRenderingCanvas();
  107311. return (!!canvas && typeof canvas.captureStream === "function");
  107312. };
  107313. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  107314. /**
  107315. * True wether a recording is already in progress.
  107316. */
  107317. get: function () {
  107318. return !!this._canvas && this._canvas.isRecording;
  107319. },
  107320. enumerable: true,
  107321. configurable: true
  107322. });
  107323. /**
  107324. * Stops the current recording before the default capture timeout passed in the startRecording
  107325. * functions.
  107326. */
  107327. VideoRecorder.prototype.stopRecording = function () {
  107328. if (!this._canvas || !this._mediaRecorder) {
  107329. return;
  107330. }
  107331. if (!this.isRecording) {
  107332. return;
  107333. }
  107334. this._canvas.isRecording = false;
  107335. this._mediaRecorder.stop();
  107336. };
  107337. /**
  107338. * Starts recording the canvas for a max duration specified in parameters.
  107339. * @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.
  107340. * @param maxDuration Defines the maximum recording time in seconds.
  107341. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  107342. * @return a promise callback at the end of the recording with the video data in Blob.
  107343. */
  107344. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  107345. var _this = this;
  107346. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  107347. if (maxDuration === void 0) { maxDuration = 7; }
  107348. if (!this._canvas || !this._mediaRecorder) {
  107349. throw "Recorder has already been disposed";
  107350. }
  107351. if (this.isRecording) {
  107352. throw "Recording already in progress";
  107353. }
  107354. if (maxDuration > 0) {
  107355. setTimeout(function () {
  107356. _this.stopRecording();
  107357. }, maxDuration * 1000);
  107358. }
  107359. this._fileName = fileName;
  107360. this._recordedChunks = [];
  107361. this._resolve = null;
  107362. this._reject = null;
  107363. this._canvas.isRecording = true;
  107364. this._mediaRecorder.start(this._options.recordChunckSize);
  107365. return new Promise(function (resolve, reject) {
  107366. _this._resolve = resolve;
  107367. _this._reject = reject;
  107368. });
  107369. };
  107370. /**
  107371. * Releases internal resources used during the recording.
  107372. */
  107373. VideoRecorder.prototype.dispose = function () {
  107374. this._canvas = null;
  107375. this._mediaRecorder = null;
  107376. this._recordedChunks = [];
  107377. this._fileName = null;
  107378. this._resolve = null;
  107379. this._reject = null;
  107380. };
  107381. VideoRecorder.prototype._handleDataAvailable = function (event) {
  107382. if (event.data.size > 0) {
  107383. this._recordedChunks.push(event.data);
  107384. }
  107385. };
  107386. VideoRecorder.prototype._handleError = function (event) {
  107387. this.stopRecording();
  107388. if (this._reject) {
  107389. this._reject(event.error);
  107390. }
  107391. else {
  107392. throw new event.error;
  107393. }
  107394. };
  107395. VideoRecorder.prototype._handleStop = function () {
  107396. this.stopRecording();
  107397. var superBuffer = new Blob(this._recordedChunks);
  107398. if (this._resolve) {
  107399. this._resolve(superBuffer);
  107400. }
  107401. window.URL.createObjectURL(superBuffer);
  107402. if (this._fileName) {
  107403. BABYLON.Tools.Download(superBuffer, this._fileName);
  107404. }
  107405. };
  107406. VideoRecorder._defaultOptions = {
  107407. mimeType: "video/webm",
  107408. fps: 25,
  107409. recordChunckSize: 3000
  107410. };
  107411. return VideoRecorder;
  107412. }());
  107413. BABYLON.VideoRecorder = VideoRecorder;
  107414. })(BABYLON || (BABYLON = {}));
  107415. //# sourceMappingURL=babylon.videoRecorder.js.map
  107416. 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\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 baseColor=texture2D(diffuseSampler,vUV);\nbaseColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \noutFragColor=texture(textureSampler,vUV)*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\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\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,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\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","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 int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  107417. 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};"};
  107418. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  107419. globalObject["BABYLON"] = BABYLON;
  107420. //backwards compatibility
  107421. if(typeof earcut !== 'undefined') {
  107422. globalObject["Earcut"] = {
  107423. earcut: earcut
  107424. };
  107425. }
  107426. return BABYLON;
  107427. });